updating useRef is not working for some reason

Viewed 31

So the following code is an attempt to make two copies of a fetch request. One of them is for state and the other is being stored in as a ref.

I can't understand why the following snippet doesn't do what I need to it to which is add the backgroundColor prop to the ref array and then set the state to that array:

useEffect(() => {
    fetchData()
    setTimeout(() => {
        clone.current.map(item => ({...item, backgroundColor: 'blue'}))
        console.log(clone.current)
        setData([...clone.current])
        console.log(data)
    }, 4000)
}, [])

This is my first time using useRef, I'm trying to understand how to keep a copy of the state that won't change through renders. This is the whole code:

import React from 'react'
import './MyProjects.css'
import {useState, useEffect, useRef} from 'react'

const MyProjects = () => {
    const [data, setData] = useState([])
    let clone = useRef(null);

    async function fetchData() {
        await fetch('https://jsonplaceholder.typicode.com/todos?userId=1')
        .then(response => response.json())
        .then(json => {
            setData(json)
            clone.current = [...json]
        })
        // .then(setData(data.map((item) => ({...item, backgroundColor: true}))))
        .catch((err) => {
            console.log(err);
          });
    }

    useEffect(() => {
        fetchData()
        setTimeout(() => {
            clone.current.map(item => ({...item, backgroundColor: 'blue'}))
            console.log(clone.current)
            setData([...clone.current])
            console.log(data)
        }, 4000)
    }, [])    

  return (
    <div className='project-container'>
        {data.length > 0 && (
                <div className='data-container'>
                {data.map(item => (
                    <div key={item.id} style={{backgroundColor : item.backgroundColor}} onClick={() => {
                    }}
                    className='dataItem'>{item.title}</div>
                ))}
                </div>
        )}
    </div>
  )
}

export default MyProjects
2 Answers

There are several issues:

  1. array.map method does not mutate the array but create a new array
            const newArray = clone.current.map(item => ({...item, backgroundColor: 'blue'}))
            console.log(clone.current); // clone is not mutated
            console.log(newArray); // however the newly created array will contain backgroundColor = 'blue' 
  1. setData is async
            setData([...clone.current]) // set data is not immediate
            console.log(data) // the variable `data` binded here anyway won't reference the updated value
  1. Your fetchData is asynchronous, your setTimeout is very prone to be buggy as you can't ensure that fetchData is completed

As a side note I don't really see the point of using a ref here since the data is already stored in a useState

2 Issues with the function:

  1. Javascript map operation would create another array instead of updating current array, use for loop to update the ref.
  2. It's not a guarantee that your fetch call will be executed before your settimeout call is executed, that's why you want to create another useeffect to process the data, you can create dataLoaded flag state and use that to just tigger this updating only once.
const [data, setData] = useState([]);
const [dataLoaded, setDataLoaded] = useState(false);
async function fetchData() {
    await fetch('https://jsonplaceholder.typicode.com/todos?userId=1')
    .then(response => response.json())
    .then(json => {
        setData(json)
        clone.current = [...json]
        setDataLoaded(true);
    })
    .catch((err) => {
        console.log(err);
    });
}

useEffect(() => {
    fetchData()
}, []);

useEffect(()=>{
    if(!dataLoaded) return;
    clone.current.map(item => ())
    for(let i = 0; i < clone.current.length; i++){
        clone.current[i] = {...clone.current[i], backgroundColor: 'blue'};
    }
    console.log(clone.current)
    setData([...clone.current])
    console.log(data)
}, [dataLoaded]);
Related