Answer the question
In order to leave comments, you need to log in
How to filter array by name in react redux?
I am getting data from the Random Users API.
Further, I want that when entering a name in the search, it would return cards that matched by name. And when erasing the name, it returned the original collection.
reducer
import { FETCH_USERS, SEARCH_VALUE, } from "../actions/actionTypes";
export function addFetchUsers(payload){
return {
type: FETCH_USERS,
payload: payload
}
}
export function getFetchUsers() {
return dispatch => {
return fetch('https://randomuser.me/api/?results=10')
.then(response => response.json())
.then(json => {
dispatch(addFetchUsers(json.results))
return json.products;
})
}
}
export function addSearchValue(payload){
return {
type: SEARCH_VALUE,
payload: payload
}
}
import { FETCH_USERS, SEARCH_VALUE } from "../actions/actionTypes";
const initialState = {
users: [],
searchValue: '',
}
const reducerFetchUsers = (state = initialState, action) => {
switch (action.type) {
case FETCH_USERS:
return {
...state,
users: state.users.concat(action.payload)
}
case SEARCH_VALUE:
return {
...state,
searchValue: action.payload
}
default:
return state;
}
};
export default reducerFetchUsers;
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getFetchUsers } from '../../../redux/actions/actionFetchUsers';
const UsersPosts = () => {
const usersPosts = useSelector(state => state.reducerFetchUsers.users);
const dispatch = useDispatch();
useEffect(() => {
dispatch(getFetchUsers());
}, [dispatch]);
return (
<div className="row">
<ul className="list">
{
usersPosts.map((user, index) => {
return (
<div className="col-lg-4" key={index}>
<li className="list__item">
<span>{user.name.first}</span>
<span>{user.gender}</span>
<span>{user.email}</span>
<span>{user.location.country}</span>
</li>
</div>
);
})
}
</ul>
</div>
)
}
export default UsersPosts;
Answer the question
In order to leave comments, you need to log in
const usersPosts = useSelector(state => {
const { users, searchValue } = state.reducerFetchUsers
if (!searchValue)
return users
return users.filter((user) => user.name.includes(searchValue))
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question