Home > Mobile >  Expected `onClick` listener to be a function. Want to load data onlick
Expected `onClick` listener to be a function. Want to load data onlick

Time:10-17

i was preparing for an interview and working with questions given on google, i have created everything perfectly well,but what i want for data to be loaded after clicking the button, but i think i am making an error, how am i supposed to do that? can anyone guide me.

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

export default function App() {
  const[count, setCount] = useState(0)
  const[randomUserDataJSON, setRandomUserDataJSON] = useState('')

  useEffect(() => {
    fetchRandomData().then(randomData=> {
      setRandomUserDataJSON(randomData ||'' )
    })
  }, [])


  const fetchRandomData = () => {
    return axios.get('https://randomuser.me/api')
    .then(({data}) => {
      console.log(data);
      return JSON.stringify(data)
    })
    .catch(error => {
      console.log(error)
    })
  } 


  return (
    <div className="App">
      <h2>how to implemenet useEffect</h2>
      <button onClick="randomUserDataJSON">Fetch Random Data</button>
      <pre>  </pre>
       
    </div>
  );
}

note also tried:

<button onClick={randomUserDataJSON}>Fetch Random Data</button>

CodePudding user response:

import "./styles.css";
import {useState} from 'react'
import axios from 'axios'

export default function App() {
  const[count, setCount] = useState(0)
  const[randomUserDataJSON, setRandomUserDataJSON] = useState('')

  const fetchRandomData = () => {
    axios.get('https://randomuser.me/api')
    .then(({data}) => {
      console.log(data);
      setRandomUserDataJSON(JSON.stringify(data)||'' )
    })
    .catch(error => {
      console.log(error)
    })
  } 


  return (
    <div className="App">
      <h2>how to implemenet useEffect</h2>
      <button onClick={fetchRandomData}>Fetch Random Data</button>
      <pre>  </pre>
       
    </div>
  );
}

  • You don't need useEffect since the action is performed on a click event
  • The onClick event needs to be wrapped in curly braces {}

CodePudding user response:

export default function App() {
  const[count, setCount] = useState(0)
  const[randomUserDataJSON, setRandomUserDataJSON] = useState('')


  const fetchRandomData = () => {
    return axios.get('https://randomuser.me/api')
    .then(({data}) => {
      console.log(data);
      return JSON.stringify(data)
    })
    .catch(error => {
      console.log(error)
    })
  } 


  return (
    <div className="App">
      <h2>how to implemenet useEffect</h2>
      <button onClick={fetchRandomData}>Fetch Random Data</button>
      <pre>{randomUserDataJSON}</pre>
       
    </div>
  );
}

  • Related