Fetching random data from API on button click - React

Marijan

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}`);
}

Sebastian Richner

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.

edited at
0

Comments

0 comments
Login to comment

Related

Fetching data from api in react

Fetching data from api promise in react API

Fetching data from YouTube API with React Hooks

React Router Fetching data from API

Fetching data from api and passing it to state in React

Fetching API data with React

React: following DRY in React when fetching data from API

Fetching API data via React

Fetching data from nested array in API React Native

React.js: Fetching Data from API with Bearer Token

fetching POST data from API (node js, react)

React useEffect infinite loop fetching data from an api

Gettin 'null' while fetching data from api with React Context

Fetching data from API in react native using redux

Applying Filter after Fetching data from api in React

fetching nested data from rest countries API using typescript in react

Accessing certain item after fetching data from API with react

Getting an empty array in React while fetching the data from the api

React, fetching from an API logs the data, but rendering it doesn't?

React fetching Data from Node Server using fetch() API

Data structure changes when fetching from Flask backend with react API

data is not fetching from useLocation in react

fetching data from graphql to react

Fetching data from object in API

Fetching data from multiple api

Fetching data from API in django

how to populate options for a react select by fetching values from an api to be visible when you click on the select box?

How to dynamically Load API Data on a button Click in React Native

React.js - Component is not appearing on button click with the data fetched by api