Home > Software engineering >  Displaying response from API in react component
Displaying response from API in react component

Time:03-30

I'm trying to display the response from the API into my react component but it's not working. If I try to use it in the console, I can see the data and its value but not in the react component, it's empty when I try to show the value in a div.

Here is the code where I'm trying to display it in my react component:

const CharacterListing = () => {
const characters = useSelector(getAllCharacters);
console.log("Hello", characters);


const renderCharacters = Object.entries(characters).map(([key, value]) => {
    console.log(value.name);
    <div>{value.name}</div>
})

return (
    <div>
        {renderCharacters}
    </div>
);
};

export default CharacterListing;

This is the code for my Character Slice Component

const initialState = {
characters: {},
};

const characterSlice = createSlice({
name: 'characters',
initialState,
reducers: {
    addCharacters: (state, { payload }) => {
        state.characters = payload;
      },
},
});

export const { addCharacters } = characterSlice.actions;
export const getAllCharacters = (state) => state.characters.characters;
export default characterSlice.reducer;

This is the code for my Home Component:

const Home = () => {
const dispatch = useDispatch();

useEffect(() => {

    const fetchCharacters = async () => {
        const response = await baseURL.get(`/characters`)
            .catch(error => {
                console.log("Error", error);
            });
        dispatch(addCharacters(response.data));
        console.log("Success", response);
    };
    fetchCharacters();
}, [])
return (
    <div>
        Home
        <CharacterListing />
    </div>
);
};

export default Home;

Thank you

CodePudding user response:

You forgot to return item into your map func

Try this :

const renderCharacters = Object.entries(characters).map(([key, value]) => {
    console.log(value.name);
    return <div key={key}>{value.name}</div>
})
  • Related