'Return arrays from custom hook
I created a custom hook that takes a string and 3 arrays of Users, called useSearchUsers
import { useCallback } from 'react';
export default function useSearchUsers() {
const searchUsers = useCallback((searchValue, assistants, interested, rejected) => {
const assistantResults = [];
const interestedResults = [];
const rejectedResults = [];
if (searchValue !== '') {
if (assistants.length > 0) {
assistants.forEach(user => {
if (user.assistantName.includes(searchValue)) {
const name = user.assistantName;
const image = user.assistantImage;
const id = user.assistantId;
assistantResults.push({
id,
name,
image
});
}
});
}
if (interested.length > 0) {
interested.forEach(user => {
if (user.interestedName.includes(searchValue)) {
const name = user.interestedName;
const image = user.interestedImage;
const id = user.interestedId;
interestedResults.push({
id,
name,
image
});
}
});
}
if (rejected.length > 0) {
rejected.forEach(user => {
if (user.rejectedName.includes(searchValue)) {
const name = user.rejectedName;
const image = user.rejectedImage;
const id = user.rejectedId;
rejectedResults.push({
id,
name,
image
});
}
});
}
}
}, []);
return searchUsers;
}
And on the screen where I want to call that hook I have a TextInput where the user can write a string. Here I have declared the assistants, interested and rejected arrays, but for obvious reasons I'm ommiting them here
import useSearchUsers from '../../hooks/assistance/useSearchUsers';
const [eventAssistants, setEventAssistants] = useState([]);
const [eventInterested, setEventInterested] = useState([]);
const [eventRejected, setEventRejected] = useState([]);
const [searchText, setSearchText] = useState('');
const searchUsers = useSearchUsers();
export default function Screen(props) {
return (
<Container>
<SafeAreaProvider>
<TextInput onChangeText={text => setSearchText(text)} />
<Button onPress={() => useSearchUsers(searchText, eventAssistants, eventInterested, eventRejected)} />
</SafeAreaProvider>
</Container>
);
}
My question is, how can I return the 3 results arrays from the hook and passing them to the screen?
Solution 1:[1]
You can return an array containing the 3 result arrays.
return [assistantResults, interestedResults, rejectedResults];
instead of return searchUsers;
And to consume it in Screen you can destructure the hook's return value.
const [assistantResults, interestedResults, rejectedResults] = useSearchUsers();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Madhan S |
