I’m struggling to figure out what I’m doing wrong in my usernames autofill search field.
I’m trying to get the users from an API using thunk and to return them.
However for some reason, I keep getting this error. I have gone through a lot of similar problems and none of the solutions worked for me.
Maybe you can help?
Here is my code:
store/main.js
import { combineReducers, createStore, compose, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import usernamesReducer from "./usernames";
const rootReducer = combineReducers({
usernames: usernamesReducer,
});
const store = createStore(
rootReducer,
compose(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
);
export default store;
store/usernames.js
export const LOADING_USERNAMES = "LOADING_USERNAMES";
export const USERNAMES_LOADED = "USERNAMES_LOADED";
const initialState = {
loading: false,
usernames: [],
};
const usernamesReducer = (state = initialState, action) => {
switch (action.type) {
case LOADING_USERNAMES:
return {
...state,
loading: true,
};
case USERNAMES_LOADED:
return {
...state,
loading: false,
usernames: action.payload.usernames,
};
default:
return state;
}
};
export const loadingUsernames = () => ({
type: LOADING_USERNAMES,
});
export const usernamesLoaded = (usernames) => ({
type: USERNAMES_LOADED,
payload: {
usernames,
},
});
export const getUsernameList = () => async (dispatch) => {
dispatch(loadingUsernames());
const response = await fetch("https://jsonplaceholder.typicode.com/users");
return dispatch(usernamesLoaded(response.json()));
};
export default usernamesReducer;
And components/UsernameAutofill
import React, { useEffect } from "react";
import { useDispatch, connect } from "react-redux";
import {
loadingUsernames,
usernamesLoaded,
getUsernameList,
} from "../../store/usernames";
const UsernameAutofill = ({
isLoading,
loadingUsernames,
usernamesLoaded,
getUsernameList,
usernames,
}) => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(getUsernameList());
// console.log(usernames);
}, []);
return (
<>
{isLoading && <div>loading</div>}
<form autoComplete="off">
<div>
<input
id="myInput"
type="text"
name="myCountry"
placeholder="Country"
/>
</div>
<input type="submit" />
</form>
</>
);
};
const mapStateToProps = (state) => ({
isLoading: state.usernames.loading,
usernames: state.usernames.usernames,
});
const mapDispatchToProps = {
getUsernameList,
loadingUsernames,
usernamesLoaded,
};
export default connect(mapStateToProps, mapDispatchToProps)(UsernameAutofill);
Can you tell what I’m doing wrong? Any help is greatly appreciated 🙂