I'm testing next13 and have the following code structure.
A parent server component calls an API to generate a list of countries, passed to a child client component displaying a select. The parent component also calls another API to generate a list of cities based on a country code, then displays city elements in a loop.
See the following code:
// /app/page.tsx
import { Search } from '@/components';
export default async function Home() {
// Countrie list generation
const countryUrl = `https://restcountries.com/v3.1/all`;
const fetchedCountries = await fetch(countryUrl);
const countries = await fetchedCountries.json();
const countryCodeList = countries.map(country => {
const { altSpellings, name: { common } } = country;
return {
[altSpellings[0]]: common
};
});
countryCodeList.sort((a,b) => {
return Object.values(a)[0].localeCompare(Object.values(b)[0]);
});
// Cities list generation.
// I'd like to update the country param in the url
const url = `https://api.api-ninjas.com/v1/city?country=FR&limit=30`;
const options = {
method: 'GET',
headers: {
'X-Api-Key': 'secret_key'
}
};
const fetchCities = await fetch(url, options);
const cities = await fetchCities.json();
return (
<main className="">
<div className="cont flex flex-col gap-2">
<h1 className="text-4xl">Cities</h1>
<Search countryCodeList={countryCodeList}/>
<div className="flex flex-col gap-2">
{cities.map(city => {
return (
<p>...</p>
)
})}
</div>
</div>
</main>
)
}
// /components/Search.tsx
"use client";
import { useState } from 'react';
const Search = ({ countryCodeList }) => {
const [searchCountry, setSearchCountry] = useState('FR');
return (
<form>
<select
name="countryCode"
id="countryCode"
>
{countryCodeList.map(countryCode => {
const code = Object.keys(countryCode)[0];
const name = Object.values(countryCode)[0];
return (
<option
value={code}
selected={code === searchCountry}
key={code}
>{name}</option>
)
})}
</select>
</form>
)
}
export default Search;
I am looking for a way to send the new country code from my child client component "Search" (at change value) to my parent server component "Home", and make "Home" call the cities API with that new country code, to generate a new list of cities to display.