Home > Back-end >  Best approach to display updated list in React via fetch again or through some other way
Best approach to display updated list in React via fetch again or through some other way

Time:06-25

After any action (add or update or delete) on list displayed in react UI, what should be the best approach to display updated list in react.

  1. Fetch the list again from database
  2. Since we are modifying the list, that means in the code there will be some variable\state list, which is being used to display that list. Just use that variable\state list, modify it and display from that variable\state list again.

or any other approach?

CodePudding user response:

I typically try to maintain a state for API calls and then use responses to help me interpret what I should do with my state.

For example - if I have something like this:

const [someState, setSomeState] = useState({})

What I’d do is retrieve the initial state and then subsequent updates are only made to the local state if the API call returns 200 (or whatever you’d like) with the request.

That’s my approach and it usually works well - I never have to fetch again after the initial fetch (for a particular piece of data).

CodePudding user response:

just use a useEffect and call the fetch function or the function to update your current list/state every time it updates

 useEffect(() => {
    callTheFetchFunctionHere()
  }, [stateOftheList])

in addition every time you add/update or delete make sure to update also the state just like this setState([...state, newData]) for adding and for the update the code will look like this

`state.forEach((item) => {
   if (item.id === id) {
       item.field1= newField1Value
       item.field2= newField2Value
           
    }
  })

  setState([...state])`

and for delete

const newArr = [...state]

        newArr.forEach((item, index) => {
          if (item.id === id) {
            newArr.splice(index, 1)
          }
        })

        setState(newArr)

just edit the condition base on your needs but that's the idea to update the state

  • Related