I managed to get data from a my json.server into the desired component using the React-Redux methods, useSelector and useDispatch along with React's useEffect method.
What's confusing me is that even though the content of the array is there, the key for it is showing as undefined.
The console output: Screenshot of console log
The component:
import React, { useEffect } from 'react';
import SetlistItem from './SetlistItem';
import { fetchSongs } from '../../actions/index'
import { useSelector, useDispatch } from 'react-redux';
const SetlistContainer = () => {
const songs = useSelector(state => state);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchSongs())
}, [dispatch])
console.log(songs)
return <div><SetlistItem /></div>
}
export default SetlistContainer;
The action:
export const fetchSongs = () => async dispatch => {
const response = await songEntries.get("/songEntries");
dispatch({ type: FETCH_SONGS, payload: response.data });
}
The reducer:
export default (state = {}, action) => {
switch (action.type) {
case FETCH_SONGS:
return { ...state, [action.payload.id]: action.payload };
case CREATE_SONG:
return { ...state, [action.payload.id]: action.payload };
default:
return state;
}
}
The db.json:
{
"songEntries": [
{
"id": 1,
"songTitle": "This is a song title",
"notes": "These are some notes"
}
]
}
fetchSongs
looks like? – norbitrialsongEntries.get("/songEntries")
does not haveid
property, instead, it contain array of objects with these properties. – Kyr