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
>Solution :
2 Issues with the function:
- Javascript map operation would create another array instead of updating current array, use for loop to update the ref.
- 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]);