Home > Software design >  How to make an axios get request on button click event in React?
How to make an axios get request on button click event in React?

Time:09-23

How do I re do my get request when I click on a button ?

import axios from "axios";
import React,{useState} from 'react';
import ReactDOM from 'react-dom';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

export default function App(){
const [randomQuote,setRandomQuote] = useState('');

React.useEffect(
   () => {
        axios.get(baseURL)
        .then((res)=> {
            setRandomQuote(res.data);
        });
    }, []
);

if (!randomQuote) return null;


return (
    <div>
        <QuoteCard 
        quote={randomQuote.content} 
        author={randomQuote.author}
        handleClick={}
        />
    </div>
)

}

My QuoteCard component has a 'generate' button, that when on clicked will generate another random quote from api.

function QuoteCard(props){
return(
    <div id="quoteCard" className="card shadow p-3">
        <div className="text-center quoteText">
            <h3 className="bold lead" style={props.textStyles}>{props.quote}</h3>
        </div>
        <div className="quoteAuthor">
            <p className="float-end" style={props.textStyles}>- {props.author}</p>
        </div>
        <div className="buttons d-flex justify-content-between">
            <div className="social-buttons d-flex justify-content-between">
                <button className="btn btn-secondary m-1">
                <i className="fab fa-twitter"></i>
                </button>
                <button className="btn btn-secondary m-1">
                <i className="fab fa-instagram"></i>
                </button>
            </div>
            <div>
                <button className="btn btn-secondary" onClick={props.handleClick}>Generate</button>
            </div>
        </div>
    </div>
);

}

ReactDOM.render(<App/>,document.getElementById('root'));

I'm quite new to using hooks in functions instead of lifecycle methods, so I'm not sure how to re-trigger the get request on the 'handleClick' prop.

CodePudding user response:

As Chris mentioned you have to create a function with name like update and paste axios up there:

import axios from "axios";
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

export default function App() {
    const [randomQuote, setRandomQuote] = useState('');

    const update = () => {
        axios
            .get(baseURL)
            .then((res) => {
                setRandomQuote(res.data);
            });
    };

    useEffect(update, []);

    if (!randomQuote) return null;


    return (
        <div>
            <QuoteCard
                quote={randomQuote.content}
                author={randomQuote.author}
                handleClick={update}
            />
        </div>
    )
}

CodePudding user response:

do it like this:

 const handleButtonClick = () => {
        axios.get(baseURL)
        .then((res)=> {
            setRandomQuote(res.data);
        });
    }

// then pass it to QuoteCard
<div>
        <QuoteCard 
        quote={randomQuote.content} 
        author={randomQuote.author}
        handleClick={handleButtonClick}
        />
    </div>

//then in QuoteCard

 <div>
  <button className="btn btn-secondary" onClick={props.handleClick}>Generate</button>
            </div>

CodePudding user response:

You can create a function like this:

const getQuote = () => {
  axios.get(baseURL)
       .then((res)=> {
          setRandomQuote(res.data);
       });
}

To fetch it for the first time when the component mounts do this:

useEffect(getQuote, [])

And then pass the function to your component through handleClick prop like this:

<QuoteCard 
  quote={randomQuote.content} 
  author={randomQuote.author}
  handleClick={getQuote}
/>

So your whole component will look like this:

import axios from "axios";
import React,{useState} from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';

export default function App(){
  const [randomQuote,setRandomQuote] = useState('');

  const getQuote = () => {
    axios.get(baseURL)
         .then((res)=> {
            setRandomQuote(res.data);
         });
  }

  React.useEffect(getQuote, []);

  if (!randomQuote) return null;

  return (
    <div>
      <QuoteCard 
        quote={randomQuote.content} 
        author={randomQuote.author}
        handleClick={getQuote}
      />
    </div>
  )
}
  • Related