skip to Main Content

Normally data fetch is good but when category data find and so filter method then get data is undefined. I think my data fetch is not right!

import { useEffect, useState } from "react";


const PostDataLoad = () => {
    const [postData, setPostdata]=useState([])
    
    useEffect(()=>{
        fetch('/public/PostDatas.json')
        .then(res=> res.json())
        .then(data=>{
            console.log(data);
            setPostdata(data)
        })
    },[])
    const Category1 = postData.filter(findCategory=> findCategory.category === 'Technology')
    
    return [postData,Category1]
};

export default PostDataLoad;

I want to get data load in filter method.

2

Answers


  1. Category1 will not be updated when you fetch the data, since there’s nothing changing it.

    My suggestion is move the filter part elsewhere, so that your PostDataLoad will only need to responsible for 1 thing (fetching data).

    Login or Signup to reply.
  2. Assuming that the exported PostDataLoad function is a hook, there are a few things that you need to fix:

    1. By convention, the function name of a hook should start with use
    2. The variable Category1 will only be computed once (the initial call) and will not be recomputed. Move the logic of calculating the return value inside the useEffect()‘s fetch call:
    import { useEffect, useState } from "react";
    
    
    const usePostDataLoad = () => {
        const [returnValue, setReturnValue]=useState([]);
        
        useEffect(()=>{
            fetch('/public/PostDatas.json')
            .then(res=> res.json())
            .then(data=>{
                console.log(data);
                setReturnValue([
                    data,
                    data.filter(findCategory=> findCategory.category === 'Technology')
                ]);
            })
        },[])
        
        return returnValue;
    };
    
    export default usePostDataLoad;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search