Home > Software engineering >  How to assign response from Api to an array using fetch function
How to assign response from Api to an array using fetch function

Time:03-18

I want to assign response in Fruits array ones I fetched the data from Api using fetch...But I am getting empty array when console.log.. I am getting the response from Api but not able to assign it to fruits I am doing this way: .then(data => Fruits);

let Fruits = []



     useEffect(() => {
      
      const requestOptions = {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '   "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
          body: JSON.stringify({"firebase_id":"foCzPM8MgOtg1"})
      };
     
          fetch('https://d.com/audis/el/lt', requestOptions)
          .then(response => response.json())
          .then(data => Fruits);    

          console.log(Fruits);
  
 
     }, []);

CodePudding user response:

Use a state

const [fruits, setFruits] = useState([]);
useEffect(() => {
      
      const requestOptions = {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '   "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
          body: JSON.stringify({"firebase_id":"foCzPM8MgOtg1"})
      };
     
          fetch('https://d.com/audis/el/lt', requestOptions)
          .then(response => response.json())
          .then(data => setFruits(data);    
     }, []);

CodePudding user response:

Maybe use a state?

    const [fruits, setFruits] = useState([])
    useEffect(() => {
      
      const requestOptions = {
          method: 'POST',
          headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer '   "eyJ0eXAiOiJKV1QiLCJhbGciOiJIwicm9sZSI6ImV4cGVydCJ9.6pYrAr_En0nl4N52oP1O7WRJA6PPFGCzUebauBIOEnc", },
          body: JSON.stringify({"firebase_id":"foCzPM8MgOtg1"})
      };
     
          fetch('https://d.com/audis/el/lt', requestOptions)
          .then(response => response.json())
          .then(data => setFruits(data));    

       
  
 
     }, []);
     console.log(fruits);

CodePudding user response:

You're not assigning data to anything. Try:

fetch('https://d.com/audis/el/lt', requestOptions)
          .then(response => response.json())
          .then(data => Fruits = data);   

Also, you should use a state do store the information.

const [fruits, setFruits] = useState();

fetch('https://d.com/audis/el/lt', requestOptions)
          .then(response => response.json())
          .then(data => setFruits(data));   
  • Related