this has to be one of the worst encounters of a bug I've ever come across. The code we're working with consists of grabbing data from the database and creating two separate states to hold the incoming data, one containing the original data, and the other to mutate that data. I created these two separate data sets to compare each other and let the user know they're able to publish changes.
Below, you'll see in the console that both of the states start out null, then receive the basic data from the back-end, and once I added a product, both of the states updated with that product... but only one is supposed to update. You'll think I'm crazy until you see the code
This is where the data is initialized (index.js):
const [initialData, setInitialData] = useState(null);
const [data, setData] = useState(null);
const [initial, setInitial] = useState(false);
const [newChanges, setNewChanges] = useState(false);
useEffect(() => {
if(isEqual(data, initialData)) {
setNewChanges(false);
} else {
setNewChanges(true);
}
}, [data, setData, initialData, setInitialData])
useEffect(() => {
console.log("Editable Data:");
console.log(data);
console.log(' ');
console.log('Initial Data');
console.log(initialData);
}, [data, setData, initialData, setInitialData])
useEffect(() => {
if(initial === true) return;
if(session === undefined) return;
if(status === 'unauthenticated') {
router.push('/');
return;
}
if(status === 'loading') return;
if(data !== null) return;
if(initialData !== null) return;
async function dashboardData() {
setInitial(true);
const result = await axios.post(`${window.location.origin}/api/admin/dashboard`, {
id: session.user.token.id,
username: session.user.token.username
}).catch((error) => {
alert(error.toString())
})
if(result !== undefined) {
if(result.status === 200) {
const resData = result.data;
setData(resData);
setInitialData(resData);
console.log("Data retrieved from database");
} else {
alert("Connection error to the database... please try again later.");
}
}
}
dashboardData();
}, [session, status])
Below is how I'm passing the data and the setData function to the Products component as props:
<Products data={data} setData={setData} />
Below is how the changes are actually applied:
export default function Products({ data, setData }) {
const products = data.products;
const [allProducts, setAllProducts] = useState(products);
const [displayProducts, setDisplayProducts] = useState(products);
function updateProducts(newArray) {
setAllProducts(newArray);
setDisplayProducts(newArray);
setData({...data, products: newArray})
}
}
Absolutely no where is setInitialData being called in the rest of the classes, it's not being passed down to any components, it's strictly called upon the database pull.