When request is sent, response is always the same on page reload in Chrome but random (as it should be) in FireFox. On button click data is always the same after page reload. I want to make a request on each button click to store different data in the state hook.
I also tried it in vanilla js and response is the same as well.
What is causing data to always be the same and not random on request? I will store previously fetched data in the state but first have to figure out why is it always the same, I would appreciate any help as I'm new to these api calls and react as well.
App.js:
import FetchColor from './common/FetchColor';
import ColorList from './components/ColorList';
import { useEffect, useState } from 'react';
function App() {
const [colorData, changeColor] = useState('');
const changeColorHandler = () => {
FetchColor(changeColor);
};
useEffect(() => {
FetchColor(changeColor);
}, []);
return (
<div className='App'>
<button onClick={changeColorHandler}>
{colorData ? colorData.tags[0].name : 'Change Color'}
</button>
<ColorList color={colorData} />
</div>
);
}
export default App;
FetchColor.js:
const FetchColor = async (changeColor) => {
const response = await fetch('https://www.colr.org/json/color/random');
const data = await response.json();
const [color] = data.colors;
changeColor(color);
};
export default FetchColor;
Vanilla JavaScript script.js:
const fetchButton = document.getElementById('fetch-api');
fetchButton.addEventListener('click', fetchColorFunc);
async function fetchColorFunc() {
const response = await fetch('https://www.colr.org/json/color/random');
console.log(`Response: ${response}`);
const data = await response.json();
console.log(`Data: ${data}`);
}
This is most likely due to caching. If you look at the requests in Chrome's Network panel of the Developer Tools, you should see that the requests are cached and therefore always return the same value.
Fetch optionally takes an init object containing custom settings that will be applied to the request, including cache. For example, you can pass cache: "no-cache"
or cache: "no-store"
to bypass caching (see documentation for details and differences) and you will get random results with each request. See the following snippet as an example:
async function fetchColorFunc() {
const response = await fetch('https://www.colr.org/json/color/random', { cache: "no-cache" });
console.log(`Response: ${JSON.stringify(response)}`);
const data = await response.json();
console.log(`Data: ${JSON.stringify(data)}`);
}
fetchColorFunc();
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments