Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Displaying response from API in react component

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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>
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading