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