'react recoil remote filter async values and update the component list
I have a component which displays counties list fetched from api.
When the app loads I bring all the countries.
I want to allow the users remotely filter the results without affecting the atom.
I was planing to call the filter family from a useState hook, but its not so possible.
https://stackblitz.com/edit/react-ongwej?file=src%2FApp.js
const all = selector({
key: 'all',
get: async () => {
const res = await axios.get('https://restcountries.com/v3.1/all');
return res.data;
},
});
const byName = selectorFamily({
key: 'byName',
get: async (filter) => {
const res = await axios.get(
'https://restcountries.com/v3.1/name/' + filter
);
return res.data;
},
});
const countries = atom({
key: 'countries',
default: all,
});
export default function App() {
const [filter, setFilter] = useState('');
const countries = useRecoilValue(all);
useEffect(() => {
//here I want to filter the countries without affecting the atom
}, [filter]);
return (
<div>
<div>
Enter any value to filter: <br />
<input
value={filter}
onChange={(x) => setFilter(x.target.value)}
type="text"
/>
<br />
</div>
{countries.map((x, i) => (
<div key={i}>{x.name.common} </div>
))}
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
