Home > OS >  Update switch state render by map in react
Update switch state render by map in react

Time:09-27

I am doing my task to change status by call api and get new data but i don't know how exactly it's can be done because it's render by an arrays.map. Sorry for my bad english, please take a look to the example i provided. Thanks a lot!

const Foo = () => {
  const [foos, setFoos] = useState([]);

  const handleClick = () => {
    try {
      // where i call api backend to change status, assume that it called success and i get new status
      // what should i do here to set new status to display in view
    } catch(e) {
      console.error('Exception '   e)
    }
  }

  useEffect(() => {
    // where i call api to set Foos, assume that it called success
  }, [])

  return (
    <>
      {foos.map((foo, i) =>
        <div key={i}>
          <p>{foo.id}</p>
          <p className={foo.status ? 'success': 'failed'} onClick={() => handleClick()}>{foo.status}</p>
        </div>
      )}
    </>
  )
}

CodePudding user response:

If I'm understanding you correctly, you want to update the status of a given foo when it is clicked?

Try this:

const Foo = () => {
  const [foos, setFoos] = useState([]);

  const handleClick = (fooIndex) => {
    try {
      const newStatus = ...; // Do something here to get new status
      const newFoos = [...foos]; // shallow copy foos
      newFoos[fooIndex] = { // shallow copy newFoos[fooIndex] element
        ...newFoos[fooIndex],
        status: newStatus,
      };
      setFoos(newFoos);
    } catch(e) {
      console.error('Exception '   e)
    }
  }

  useEffect(() => {
    // where i call api to set Foos, assume that it called success
  }, [])

  return (
    <>
      {foos.map((foo, i) =>
        <div key={i}>
          <p>{foo.id}</p>
          <p className={foo.status ? 'success': 'failed'} onClick={() => handleClick(i)}>{foo.status}</p>
        </div>
      )}
    </>
  )
}

It comes down to just sending the index of the foo that was clicked to the handleClick callback and then using that to update the correct foo.

  • Related