youngho Park
youngho Park

Reputation: 35

useState doesn't update its value in React

I want to update list came from socket but setList doesn't work. Is it closure thing? then how could i fix it?

function List(props) {
  const [list, setList] = useState([]);

  useEffect(() => {
    if (props.socket) {
      props.socket.on("list", (data) => {
        setList(data);
      });
    }
  }, [props.socket]);

  const renderList = (list) => {
    if (!list) return null;
    

    list.map((room) => {
      return <Room pop={room.length} />;
    });
  };

  return <div>{renderList()}</div>;
}

Upvotes: 0

Views: 128

Answers (2)

Jayce444
Jayce444

Reputation: 9063

You shouldn't be using a parameter for your renderList function. By doing so, the list you're referencing inside it refers to that parameter, rather than the state value. You also aren't returning anything from that function, you don't return the call to .map. Try something like this:

const renderList = () => {
  if (!list) return null;

  return list.map((room) => <Room pop={room.length} />);
};

Also make sure the props.socket.on(...) function is actually firing and calling the state update function

EDIT: as others mentioned, check your dependencies for that useEffect. I'm guessing props.socket itself doesn't actually ever change, so you can end up with stale data

Upvotes: 1

Chanandrei
Chanandrei

Reputation: 2421

Yes its a closure thing. Try to include your list state on the useEffect dependency.

see the answer to this question for reference

Upvotes: 0

Related Questions