I am working through a course on Udemy (that has been archived and the instructor doesn’t really help with it anymore) that I am having a problem with. The instructor had two “optional” sections one on React Hooks, and one on Redux. For the Redux section (which comes after the Hooks section) the instructor switched back to the non-Hooks version of the app, but I’m trying to make the changes while keeping hooks in use.
I am having some trouble with linking back to a search box so that it dynamically updates the page as the user types. For some reason the text field input isn’t making its way back into the “const filteredRobots” function. I get a “onSearchChange is not defined” error even though the function should be firing off from dispatch function. (At least I think)
This is App.jsx
import React, { useState, useEffect } from 'react';
import {Provider, connect, useStore, useDispatch} from 'react-redux';
import CardList from './CardList.jsx';
import SearchBox from './SearchBox.jsx';
import Scroll from './Scroll.jsx';
import ErrorBoundry from './ErrorBoundry.jsx';
import { setSearchfield } from './actions.js';
const mapStateToProps = state => {
return{
searchField: state.searchField
}
};
const mapDispatchToProps = (dispatch) => {
return {
onSearchChange: (event) => dispatch(setSearchfield(event.target.value))
}
}
function App(){
const store = useStore();
const [robots, setRobots] = useState([]);
const [searchField, setSearchField] = useState('');
const dispatch = useDispatch();
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => response.json())
.then(users => {setRobots(users)});
}, [])
const filteredRobots = robots.filter(robot => {
return robot.name.toLowerCase().includes(searchField.toLowerCase());
})
return(
<div className="tc">
<h1>RoboFriends</h1>
<SearchBox searchChange={() => dispatch(onSearchChange)} />
<Scroll>
<ErrorBoundry>
<CardList robots={filteredRobots} />
</ErrorBoundry>
</Scroll>
</div>
)
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
And this is “reducers.js”
import { CHANGE_SEARCHFIELD } from './constants.js';
const initalState = {searchField: ''}
export const searchRobots = (state = initalState, action = {}) => {
switch(action.type){
case CHANGE_SEARCHFIELD:
return Object.assign({}, state, {searchField: action.payload});
default:
return state;
}
}
And actions.js
import { CHANGE_SEARCHFIELD } from './constants.js';
export const setSearchfield = (text) => ({ type: CHANGE_SEARCHFIELD, payload: text });
Thoughts on what needs to be added or changed?