I'm using react-select to help create a filtering system for my website. However, I have some issues with it at the moment.
Background:
Here is my code for contentful:
export async function getStaticProps() {
const client = createClient({
space: process.env.TOKEN,
accessToken: process.env.TOKEN,
});
const res = await client.getEntries({
content_type: "indieProjects",
});
return {
props: {
indieProjects: res.items,
},
};
}
Here is my code for React-select
<Select
isMulti
placeholder="Search..."
options={indieProjects.map((items) => {
return { label: items.fields.type, label: items.fields.type };
})}
/>
My first issue is.. when using this I get duplicates pop up when I only want 1 of each to show. I have attached an example of the issue . I know that it is to do with the options and mapping over indieProjects - but Im not sure the best way to fix it.
My second issue is... how do I then render the component once the selection has been made? It will be multi-select so the user can select as many options.
Thanks in advance for the help.
I would suggest memoizing the options for react select if you need to filter them (which you do in order to get rid of your duplicates.)
Something like this should solve your first problem. for your second problem, you should add an onChange function and assign a value to your Select. I would suggest using useState for this. (using state will also give you access to the value(s) that they choose)
Also a huge problem it seems you have is that you use label
and label
instead of label
and value
for your options object.
const [state,setState] = useState([])
const options = useMemo(
() =>
([...new Set(indieProjects.map(item=>item.fields.type))]).map((type) => {
return { label: type, value: type };
}),
[indieProjects]
);
return (
<Select
isMulti
onChange={(e)=> e && setState(e)}
value={state}
placeholder="Search..."
options={options}
/>)
Here is a link to a code sandbox with the Select rendering.
https://codesandbox.io/s/dreamy-leftpad-l2pzq?file=/src/App.js