0

code

import React from "react";
import useUsersData from "./useUsersData";

export const User = ({ _id, name, age, email }) => {
const [userData, setUserData] = useUsersData();

const handleDelete = (id) => {
const proceed = window.confirm("Are you sure?");
if (proceed) {
  const url = `http://localhost:5000/users/${id}`;

  fetch(url, {
    method: "DELETE",
  })
    .then((res) => res.json())
    .then((data) => {
      console.log(data);
    }); }
const remaining = userData.filter((userData) => userData._id !== id);
console.log(userData);
console.log(remaining);
setUserData(remaining);
console.log(userData);
 };

 return (

    <p onClick={() => handleDelete(_id)}>
    X
  </p>
  </div>
  );
 };

the custom hook:

 import { useEffect, useState } from "react";

   const useUsersData = () => {
  const [userData, setUserData] = useState([]);

 useEffect(() => {
  fetch("http://localhost:5000/users")
  .then((res) => res.json())
  .then((data) => setUserData(data));
  }, []);

 return [userData, setUserData];
 };

 export default useUsersData;

not updating useState() custom hook when I use setState(somedata) the custom hook useState does not get updated. I don't know what I did wrong.

You can see in the console log that set user data is not changing. here is a screenshot console.log

Chizaram Igolo
  • 907
  • 8
  • 18

1 Answers1

0

Whenever you call the dispatch function of useState, its effects on the state will only be noticeable on the next function call.

So if you console.log or otherwise try to use the state immediately after a dispatch, it will not have the latest data.

If you want to use the latest state as soon as it is updated, you need to useEffect while passing the state in the dependency array.

const Example = () => {
  const [userData, setUserData] = React.useState(['1', '2', '3']);

  const handleDelete = () => {
    const remaining = userData.filter((id) => id !== '3');
    console.log(userData); // will print ['1', '2', '3']
    console.log(remaining); // will print ['1', '2']
    setUserData(remaining);
    console.log(userData); // will still print ['1', '2', '3']
  };

  React.useEffect(() => {
    console.log('useEffect', userData); // will print "useEffect ['1', '2']"
  }, [userData]);

  return <p onClick={handleDelete}>X</p>;
};

This is the same issue as posted in The useState set method is not reflecting a change immediately