Home > Net >  React state showing only last value
React state showing only last value

Time:10-05

I tried to loop over my object and add its elements to a array. Then tried to render those array elements in JSX but only the last element is rendered.

Here are the code snippets,

const [filters, setFilters] = useState({
    Easy: true,
    All: true,
    medium: false,
    hard: true,
  });
  const [selected, setSelected] = useState([]);

  useEffect(() => {
    for (let el in Object.keys(filters)) {
      if (filters[el]) {
        //alert(el);
        //var tmp = [...selected];
        //tmp.push(el);
        //setSelected(tmp);
        setSelected([...selected, el]);
      }
    }
  }, []);


       <div style={{ display: "flex" }}>
          {selected.map((el) => (
            <h1>{el}</h1>
          ))}
        </div>

Here only the hard is rendered on the screen but the alert gives correct values.

CodePudding user response:

You need to take into consideration the previous state too in your situation because otherwise you will loose info, so the correct way of doing this is not

setSelected([...selected, el]);

but rather

setSelected(prevState => [...prevState, el]);

I also changed a little bit the iteration for keys

Edit react-state-showing-only-last-value

  • Related