Home > Back-end >  How to fetch data and compare to another data?
How to fetch data and compare to another data?

Time:11-22

I have a simple react project where i fetch some data from array from another api. And I am stack with the following problem.

I need to compare my fetched data with another data at another endpoint. Here is my code to be clear with it:



const App = () => {
const [countries, setCountries] = useState([])

useEffect(() => {
    axios
      .get('https://date.nager.at/api/v3/AvailableCountries')
      .then((response) => {
        console.log(response.data)
        setCountries(response.data)
      })
      .catch(error => console.log(`Axios error: ${error}`))
  }, [])

return (
      <div className='content'>
        <div>
          {filteredCountries.map((item, index) => 
              <div key={index}>
                  <li item={item}>{item.name}</li>
              </div>
          )}
        </div>
      </div>
  )
}

export default App

So the task: By clicking on country i need to fetch and display holidays below the selected country. Endpoint for holidays: https://date.nager.at/api/v3/NextPublicHolidays/{countryCode}

I have tried something like this:

async function fetchHolidays() {
    const response = await axios.get('https://date.nager.at/api/v3/NextPublicHolidays/AT')
    console.log(response.data)
}
<li item={item} onClick={fetchHolidays}>{item.name}</li>

CodePudding user response:

You'll need another state for the holiday data. Because the country codes are unique, that'd be a good way to organize them.

const App = () => {
  const [countries, setCountries] = useState([]);
  const [holidays, setHolidays] = useState({});
  const makeFetchHolidayForCountryCode = (code) => () => {
    axios.get('https://date.nager.at/api/v3/NextPublicHolidays/'   code)
    .then((result) => {
      setHolidays({ ...holidays, [code]: result.data });
    })
    // .catch(handleErrors);
  };

Then just call makeFetchHolidayForCountryCode when creating the click handler.

<li
  item={item}
  onClick={makeFetchHolidayForCountryCode(item.countryCode)}
>{item.name}</li>

and display the results by mapping over holidays[item.countryCode].

{
  holidays[item.countryCode]?.map(({ date, name }) => (
    // construct your desired JSX here
  ))
}

You should also fix your HTML - it isn't valid at the moment. A <li> should only be a child of a list, not of a <div>. Consider using a <span> or a <div> instead.

  • Related