Home > Software design >  React: data.map() is not a function only after POST method
React: data.map() is not a function only after POST method

Time:12-29

Whenever I successfully update an user at UpdateUser component and I navigate back to my Home component, I get the "Uncaught TypeError: data.map is not a function"... When I navigate to other components and back to Home, this does not happen; it only occurs after updating any user. Video:
https://youtu.be/uUf9Yx91-jw

Home.js component:

import axios from "axios";
import { useQuery } from "@tanstack/react-query";
import uniqid from "uniqid";
import { useNavigate } from "react-router-dom";

export const Home = () => {
  const navigate = useNavigate();
  const { data, refetch } = useQuery(["user"], async () => {
    try {
      return await axios.get("/api/home").then((res) => res.data);
    } catch (error) {
      console.log(error);
    }
  });

  const DisplayUser = () => {
    return (
      <div>
        {data &&
          data.map((user) => {
            return (
              <div className="userCard" key={uniqid()}>
                <h2>Name: {user.name}</h2>
                <p>Email: {user.email}</p>
                <p>Id: {user.userid}</p>
                <button className="btn" onClick={() => deleteUser(user.userid)}>
                  Delete
                </button>

                <button
                  className="btn"
                  onClick={() => {
                    navigate(`/updateuser/${user.userid}`);
                  }}
                >
                  Update
                </button>
              </div>
            );
          })}
      </div>
    );
  };

  const deleteUser = (id) => {
    axios.delete("/api/deleteuser", { data: { id: id } }).then((res) => {
      refetch();
    });
  };

  return (
    <div className="userCardContainer">
      <h1>Home Page</h1>
      <DisplayUser />
    </div>
  );
};

UpdateUser.js

import axios from "axios";
import { useState } from "react";
import { useParams, useNavigate } from "react-router-dom";
import { useQuery } from "@tanstack/react-query";

export const UpdateUser = () => {
  const navigate = useNavigate();
  const params = useParams();
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [userid, setUserId] = useState("");

  const { data } = useQuery(["user"], () => {
    return axios.get(`/api/getuser/${params.userid}`).then((response) => {
      setName(response.data.name);
      setEmail(response.data.email);
      setUserId(response.data.userid);
      return response.data;
    });
  });
  const onSubmit = (e) => {
    e.preventDefault();
    const user = {
      name: name,
      email: email,
      password: password,
      userid: userid,
    };
    axios.post("/api/updateuser", user).then((res) => console.log(res));
    navigate("/");
  };

  return (
    <div className="formContainer">
      <h1>{params.userid}</h1>
      <form className="addUserForm" onSubmit={onSubmit}>
        <input
          className="formInput"
          type="text"
          onChange={(e) => setName(e.target.value)}
          value={name || ""}
        />
        <input
          className="formInput"
          type="text"
          value={email || ""}
          onChange={(e) => setEmail(e.target.value)}
        />
        <input
          className="formInput"
          type="password"
          placeholder="Type new password"
          onChange={(e) => setPassword(e.target.value)}
        />
        <input className="formInputBtn" type="submit"></input>
      </form>
    </div>
  );
};

I thought the issue was at UpdateUser component, yet once I reload the Home component, I see the updated user, so I think it must be related to the useQuery/axios GET request... I have already spent a couple of hours trying to figure this one out without any help!

CodePudding user response:

This error typically occurs when your trying to loop over an object using map function. Keep in mind that map is only available on arrays. Please refer to this answer here

data.map is not a function

Here are 2 things you can do:

1) after updating the user do a console.log(data) before return keyword in Home.js component to see what's the value of data is

2) Keep in mind that instead of doing

   {data &&
      data.map}

you can simply do:

   { data?.map }

Note: If the value of data is an object after updating a user you need to add a condition such as only use map if data is an array, that should do it. Something like:

 { Array.isArray(data) && data?.map(...)    .....}

Hope that helps!

  • Related