Home > front end >  reactjs can't show data in my jsx using map method
reactjs can't show data in my jsx using map method

Time:09-30

Hi I am using redux but can't show data in my jsx using map method. getting this error Cannot read properties of undefined (reading 'data') see also screenshot2 where I can see my data is receiving from api. If my data is receiving then why getting this error?

const PostAds = () => {
  const dispatch = useDispatch()
  const [category,setCategory] = useState([])
  useEffect(()=>{
    const fetchcategory = async ()=>{
    const data = await axios.get("http://127.0.0.1:8000/ads_category/")
    const r = dispatch(ads_category(data)) 
    setCategory(r)
    } 
    fetchcategory()

  },[])

  useEffect(() => {
   
     console.log("redux_data",category)
  }, [category]);

  
    return (
      <>
       {category.payload.data.map((data)=>{
        return(data.main_category)
       })}
     </>
     
  )
}

export default PostAds

seceenshot2

enter image description here

screnshot1 enter image description here

CodePudding user response:

Be consistent with your types.

According to the data in the screen shot, you expect category to be an object with a property called payload. But you're initially setting category to an empty array:

const [category,setCategory] = useState([])

So should it be an object or an array? An array will never have a property called payload.

First, don't set it to an array if you don't want it to be an array. If you give it no initial value at all, it will be undefined:

const [category,setCategory] = useState()

Then in the JSX, use optional chaining when referencing it so that if it's undefined it just outputs nothing:

<>
  {category?.payload.data.map((data)=>{
    return(data.main_category)
  })}
</>

If there are cases where the payload property might not be defined, or any other property, you could use the same approach.

CodePudding user response:

Firstly, category is a simple state variable in this case, and doesn't have to do anything with redux. You must use the state stored in redux, not the component itself. For that matter, dispatch(ads_category(data)) should suffice.

Secondly, your useEffect is called AFTER the first render, which means you are only fetching data into category after the component has already tried to render once. So category.payload.data.map will obviously error out since category doesn't have the value you want it to have.

Since this is a basic problem, try to understand why you're getting this error so it doesn't repeat in the future.

For an immediate solution, try going with this:

{category?.payload?.data?.map((data)=>{
    return(data.main_category)
})}
  • Related