0

Temp.js

import React, {useEffect, useState} from 'react';
import axios from 'axios'
const Temp=()=> {
    const APP_ID='8232312'
    const APP_KEY='6a4e7c08d71463dada3b481f85a9b16'
    const [receipe, setReceipe] = useState([])


    useEffect(() => {
        console.log("use effect")
axios.get(`https://api.edamam.com/search?q=chicken&app_id=${APP_ID}&app_key=${APP_KEY}`)
        .then(response => {
          console.log('get receipe by promise', response)
          console.log("use state variable receipes")
          setReceipe(response.data)
          console.log("after use state receipe = " , receipe)
        })
        .catch(e => console.log(e))


    });

    return (

        <div>

        </div>
    )
}

export default Temp

App.js

import React from 'react';
import './App.css';

import Temp from './Component/Temp';

const App = ()=> {

  return (
<div className='App'> 
<Temp></Temp>
</div>
  );
}

export default App;

Console output-

use effect
Temp.js:13 get receipe by promise {data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
Temp.js:14 use state variable receipes
Temp.js:16 after use state receipe =  []
Temp.js:10 use effect
Temp.js:13 get receipe by promise {data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
Temp.js:14 use state variable receipes
Temp.js:16 after use state receipe =  {q: "chicken", from: 0, to: 10, more: true, count: 168106, …}
Temp.js:10 use effect
Temp.js:13 get receipe by promise {data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
Temp.js:14 use state variable receipes
Temp.js:16 after use state receipe =  {q: "chicken", from: 0, to: 10, more: true, count: 168106, …}
Temp.js:10 use effect
Temp.js:13 get receipe by promise {data: {…}, status: 200, statusText: "", headers: {…}, config: {…}, …}
Temp.js:14 use state variable receipes
Temp.js:16 after use state receipe =  {q: "chicken", from: 0, to: 10, more: true, count: 168106, …}


in the console output, for the first time, the recipe is set to empty while the second-time recipe is set with the response from the HTTP request. But I need setReceipe(response.data) to set receipe to response.data for first time also

3 Answers 3

1

Short Answer

You cannot and should not even try to. On first load, you do not even have the data to populate your state. Hence, you cannot do that.

Long Answer

HTTP Network calls (axios GET/POST/PUT/DELETE or any other network call using any other library) are asynchronous. When you load your component (application), XHR calls are placed in queue to be executed. During this time your UI renders and your state is initialized to some default value. Once the XHR call is completetd successfully, then actually you receive the data from server. Now you can update your state with response.data.

Also, do not worry about this behavior. This is common for any application in place practically.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

0

It's not possible

The render and rerender happen one after the other. The receiving of the data takes time and so your initial data will be empty.

Quick fix

A way to stop this breaking is to make sure that you have a default value, like you already have.

const [receipe, setReceipe] = useState([])
...
receipe.map((item) => <p>{item.someText}</p>)

If recipe is defaulted to [] or if its filled with data [{someText: 'text'}] the map over data will not break. You can also choose to not render the component if there's no data

return recipe ? <Component /> : null

Comments

0

Please check the below example that how you can call api with GET request using axios:

import React, {useEffect, useState} from "react";
import axios from 'axios';

function PostListPage() {
    const [posts, setPost] = useState([]);
    let signal = axios.CancelToken.source();

    useEffect(() => {
        let isSubscribed = true;
        axios.get('https://jsonplaceholder.typicode.com/posts', {
            cancelToken: signal.token,
        })
            .then(res => {
                const posts = res.data;
                setPost(posts);
            }).catch(err => {
            console.log(err);
        });
        return function cleanup() {
            isSubscribed = false;
            signal.cancel('Api is being canceled');
        }
    }, []);

    return (
        <React.Fragment>
            <ul>
                {
                    posts.map(post => <li key={post.id}>{post.title}</li>)
                }
            </ul>
        </React.Fragment>
    );
}
export default PostListPage;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.