简体   繁体   中英

Context Provider not re-rendering on state change

This is the code.

const [coins, setCoins] = useState([])
const [sortedCoins, setSortedCoins] = useState([])

With useEffect , I request from an API code and store it in coins, then I store that same data in sortedCoins , then with this function I sort through that (There might be some missing } because its only one part of the function, essentially this is the part that sorts the data by name).

const sort = (e) => {
    let name = e.target.getAttribute("name");

    if (name === "cryptonames") {
      let temp = coins;

      temp = temp.sort((a, b) => {
        return a.name.localeCompare(b.name);
        
      });

      setSortedCoins(temp);
}

Now on another component I do this:

{sortedCoins.map((coin) => {
        return <SpecificCoin key={coin.id} {...coin}></SpecificCoin>;
      })}

My problem is, even though the sorting is successful and the sortedCoins is an array sorted by names (I am using CoinGecko API for cryptocurrencies), my SpecificCoin list is not re-rendered, it stays the default way.

Any help is much appreciated!

Can't say that I understood your question completely to be honest, but I can see there's something wrong with your sort function

      let temp = coins;

Do not equate an array with a variable because it doesn't create a copy of the array, and any changes to temp means you're directly mutating the coins state variable, which will not cause a re-render if any changes were to be made to it. Try

let temp = [...coins]

or

let temp = coins.slice()

Secondly,

temp = temp.sort((a, b) => {
...

sort() on an array changes the array itself, so no need to do this, instead go for

 temp.sort((a, b) => {
    ...

Then when you do setSortedCoins(temp) , it might cause a re-render, because you will have followed the prescribed ways of updating an array state variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM