0

I'm facing a problem of API response array(in my case it's cities) is storing and mapping the previous result of the weather searches. Which i don't want. i want to replace the previous results with the current search API response results. here is the code.(im new to the reactjs)

import React from 'react';
import  { useState,useEffect } from 'react';
import ReactDOM from 'react-dom';

const Content=(props)=>{

  const [cities, setItems] = useState([]);

  // const API=api;
  const appi=props.api;
  console.log(props.api);
  console.log(cities)

  useEffect(() => {
    if (appi) {
      (async () => {
        try {
          const response = await fetch(appi);
          const result = await response.json();
          const updatedCities =cities.concat(result)
          setItems(updatedCities);
        } catch(err) {
          console.error(err);
        }
      })();
    }
  }, [appi]);


    return (
        <ul>
        {cities.map(citi => (
          <li key={citi.city.id}>  
            The city id is  {citi.city.id}   
            The city name is  {citi.city.name}   
            The temparature is {citi.list[0].main.temp}
          </li>
        ))}
      </ul>
  
      
    )
  }


export default Content;

Here is the output of the code As you can see there are two objects has been mapped. But there should be only one objects. How to fix that. p.s I already tried putting setItems([ ]) into the useEffect but didn't work. Thank you

2 Answers2

0

I've solve the problem. here is the answer.The "array.shift()" - it removes the first element of the array. so it removes the first element of the "cities" array before concatinating them.

    useEffect(() => {
    if (appi) {
      (async () => {
        try {
          const response = await fetch(appi);
          var result=[];
          result = await response.json();
          cities.shift();
          const updatedCities =cities.concat(result)
          setItems(updatedCities);
        } catch(err) {
          console.error(err);
        }
      })();
    }
  }, [appi]);
0

Please wrap result into array as it is an object coming from API.

  useEffect(() => {
    if (appi) {
      (async () => {
        try {
          const response = await fetch(appi);
          const result = await response.json();
           setItems([result]);
        } catch(err) {
          console.error(err);
        }
      })();
    }
  }, [appi]);
Diwakar Singh
  • 684
  • 1
  • 5
  • 19