My useState hook is not updating itself and when i am trying to get data using filter, its not working

Viewed 36

When I am trying to get data from an array using filter and find, it's not getting filtered also the _ids are the same when I cross-checked the array, also useState is also not updating

1. How should I filter one element from an array, Am I doing this right?
2. useState is not working, not updating data

I am getting every data from context (c1)

sd is returning array of single object, so to get one first index I am returning sd[0]

const ReadTemplate = (props) => {
  const c1 = useContext(PostsContext);
  const [first, myData] = useState({});

  const first_load_func = () => {
    const id = props.match.params.id;
    const sd = c1.data.filter((c1) => id === c1._id);

    const business_props = c1.business_data.filter((c1) => id === c1._id);
    const startups_props = c1.startups_data.filter((c1) => id === c1._id);
    const tech_props = c1.tech_data.filter((c1) => id === c1._id);
    const sports_props = c1.sports_data.filter((c1) => id === c1._id);

    if (sd) {
      return sd[0];
    } else if (business_props) {
      return business_props[0];
    } else if (startups_props) {
      return startups_props[0];
    } else if (tech_props) {
      return tech_props[0];
    } else if (sports_props) {
      return sports_props[0];
    } else {
      return <MyAlert />;
    }
  };
  const func = (data) => {
    if (data) {
      setTimeout(() => {
        myData(data);
      }, 1000);
      console.log('ye first hai');
      console.log(first._id);
      console.log('ye data hai');
      console.log(data);
    } else {
      console.log('No');
    }
  };
  useEffect(() => {
    first_load_func();
    func(first_load_func());
  }, [first]);

  return (
    <>
      <PostDesign props={first} />
    </>
  );
};

export default ReadTemplate;
1 Answers

My guess from your code is that you should assign the filtered data when the component is rendered, not when first changes:

useEffect(() => {
    func(first_load_func());
}, []);

It may be useful to convert ids toString() before comparing them:

const sd = c1.data.filter((c1) => id.toString() === c1._id.toString());
Related