Home > Software design >  Onclick of the button, show the data in console that is fetched by api
Onclick of the button, show the data in console that is fetched by api

Time:10-08


Heading

import react, { useEffect } from 'react';
import './styles.css';

export default function App() {
  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos')
      .then((response) => response.json())
      .then((json) => json(data));
  }, []);

  return (
    <div className='App'>
      <button
        onClick={() => {
          console.log(data);
        }}
      >
        submit
      </button>
    </div>
  );
}

the if i try to code the same thing taking a function then it is displaying error

CodePudding user response:

You should store the data in a state variable to access them through your component:

import react, { useState, useEffect } from 'react';
import './styles.css';

export default function App() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos')
      .then((response) => response.json())
      .then((json) => setData(json));
  }, []);

  return (
    <div className='App'>
      <button
        onClick={() => {
          console.log(data);
        }}
      >
        submit
      </button>
    </div>
  );
}
  • Related