I’m trying to retrive the firstname from the object returned in an array object from an API, its response is being loaded with axios in the userContext component and then I pass the response with the state in the variable record, so in the collectionPortfolioFollowUps I’m logging the name in the variable const userFirstName = record.firstname; however, it is returning in the console as undefinied.
Here is my code:
UserContext.jsx:
export const UserContext = createContext();
export const UserContextProvider = (props) => {
const URL = "/api/authuser"; //http://localhost:8080
const axiosPrivate = useAxiosPrivate();
const initialState = {
record: [],
};
const [state, dispatch] = useReducer(UserReducer, initialState);
const getUserDetails = async (username) => {
try {
const response = await axiosPrivate.get(URL + "/user/" + username);
console.log(response.data);
dispatch({
type: GET_RECORD,
payload: response.data,
});
} catch (err) {
console.log(err);
}
};
return (
<UserContext.Provider
value={{
record: state.record,
getUserDetails,
}}
>
{props.children}
</UserContext.Provider>
);
};
UserReducer.jsx:
import { GET_RECORD, GET_RECORD_LIST } from "../const/actionTypes";
export default (state, action) => {
switch (action.type) {
case GET_RECORD:
return {
...state,
record: action.payload,
};
default:
return state;
}
};
CollectionPortfolioFollowUps.jsx:
const CollectionPortfolioFollowUps = () => {
const { getUserDetails, record } = useContext(UserContext);
const { auth } = UseAuth();
const extractedUsername = auth.username; // From the global auth hook, I get the logged in user from the Login component
console.log(" Username " + extractedUsername);
const userFirstName = record.firstname;
console.log("User's ID" + extractedUserById);
useEffect(() => {
getUserDetails(extractedUsername);
}, []);
return <div></div>;
};
export default CollectionPortfolioFollowUps;

