Home > Blockchain >  Cannot read properties of undefined (reading > 'map')
Cannot read properties of undefined (reading > 'map')

Time:07-11

I'm fetching data from an API and want to show them as texts, the title and desc worked fine but the categories didn't, the error I get is:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

The Code:

export default function SinglePost() {

      const [post, setPost] = useState({});
      const [title, setTitle] = useState("");
      const [desc, setDesc] = useState("");
      const [categories, setCategories] = useState("");
      
        useEffect(() => {
        const getPost = async () => {
          const res = await axios.get("/posts/"   path);
          setPost(res.data);
          setTitle(res.data.title);
          setDesc(res.data.desc);
          setCategories(res.data.categories);
        };
        getPost()
      }, [path]);
      
      <div className="singlePost">
                <div className="singlePostInfo">
               <div className="postCats">
              {post.categories.map((c) => (
                    <span className="postCat" key={c._id}>
                      Category: {c.name}
                      </span>
                  ))}
              </div> 
      </div>
    }

I don't know where my mistake is!

CodePudding user response:

you need to update your render method to render categories from the state and the default value of categories state should be [] instead of ""

Change const [categories, setCategories] = useState("") to const [categories, setCategories] = useState([])

Change post.categories.map to categories.map and it should work!

  • Related