deadant88
deadant88

Reputation: 1008

Run a fetch call onLoad - React

I am new to React.

I am trying to run a fetch call to get some data when my react page loads. I am not sure I am calling the event correctly though.

Here is how I am calling it:

export default function GetRecipe(props) {
  let { name } = useParams()
  const [searchQuery, setSearchQuery] = useState('')
  const [recipeName, setRecipeName] = useState('')
  const [methodStepsList, setMethodStepsList] = useState([])
  const [ingredients, setIngredients] = useState([])

  const retrieveRecipe = function (e) {
    console.log('getting recipe')
    e.preventDefault()
    console.log(searchQuery.length)
    let queryString
    if (searchQuery.length) {
      queryString = `http://localhost:3001/getbasicrecipe/?name=${searchQuery}`
    } else {
      queryString = `http://localhost:3001/getbasicrecipe/?name=${name}`
    }
    fetch(queryString, {
      method: 'GET',
      headers: { 'Content-type': 'application/json' },
    })
      .then((resp) => resp.json())
      .then((json) => {
        console.log(json)
        let result = json
        let recipeName = result[0].recipe_name
        let recipeMethod = result[0].recipe_method.split(/\r?\n/)
        console.log(recipeMethod)
        setRecipeName(recipeName)
        setMethodStepsList(recipeMethod)
        setIngredients(json)
      })
  }

  return (
    <div>
      <div className="recipe-form-container">
        <form className="recipe-form">
          [...]
          </div>
        </form>
      </div>
    </div>
  )

I read about componentDidMount() but could not figure out how to include it in my code.

Thanks!

Upvotes: 1

Views: 6084

Answers (5)

Ahmed Faisal Amit
Ahmed Faisal Amit

Reputation: 1

As you are using Functional Component of React JS, you don't need to handle the component lifecycle method manually. For functional component, there is useEffect hook which will handle the lifecycle of the component.

import React, { useEffect } from 'react';

export default function GetRecipe(props) {
    useEffect(() => {
        retrieveRecipe();
    },[]);

    return <></>;
}

The above code will call the retrieveRecipe function only once after rendering this component.

Upvotes: 0

Hamza Manan
Hamza Manan

Reputation: 420

    import React, {  useEffect } from "react";
    
    function YourComponent() {
     
   
      useEffect(() => {
      retrieveRecipie(e).then((res)=>{
       console.log(res);
  }
)
      }, []);
    
      return (
       <div></div>
      );
    }
    
    export default YourComponent;

mak you retrieveRecipie function

const retrieveRecipie= (yourParams) => {
  return fetch(
    `URL from where you are fetching data`,
    {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-type": "application/json",
      },
body: JSON.stringify(yourParams),
    }
  )
    .then((response) => {
      return response.json();
    })
    .catch((err) => {
      console.log(err);
    });
};

Upvotes: 2

Hakim Abdelcadir
Hakim Abdelcadir

Reputation: 1326

If you are using a class component then, as you mentioned you can use the componentDidMount() lifecycle method like this:

componentDidMount() {
    // Runs after the first render() lifecycle
    retrieveRecipe();
}
...
render(){
...
}

Docs: https://reactjs.org/docs/state-and-lifecycle.html#adding-lifecycle-methods-to-a-class

However if you are using a function component you should use instead the useEffect hook like this:

useEffect(() => {
   retrieveRecipe();
}, []); // by using an empty array as dependency this useEffect will act as the componentDidMount function
...
return (
...
)

Docs: https://reactjs.org/docs/hooks-effect.html

Upvotes: 3

Tzachi
Tzachi

Reputation: 32

this is a classic case of using useEffect hook -

as in before the return function use - useEffect(()=>{ retrieveRecipe(); },[]);

it comes instead of componentDidMount

I recommend to play a bit with react.js tutorial to get the hang of it before creating your own projects.

Upvotes: 0

Hans Murangaza DRCongo
Hans Murangaza DRCongo

Reputation: 860

If you are using Class based component

componentDidMount(){
 //Your code here
}
render(){
return ...
}

If using function component

useEffet(()=>{
   //your code here
}, [])

return (...)

Upvotes: 0

Related Questions