Search code examples
javascriptreactjsredux

data appear undefined in my component, but it normally appears inside the mapStateToProps function


I am making a basic Songs select app using react and redux, but I have some problems. In the mapStateToProps() function in my Songlist Component, the state argument, passed, usually gets a value But when I try to Log Props in Component I get a value of undefined

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import {Provider} from 'react-redux'
import {createStore} from 'redux'
import reducers from './reducers'

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={createStore(reducers)}>
      <App />
    </Provider>
  </React.StrictMode>
);

Action

export const selectSong = (song) => {

    return {
        type: 'SELECT_SONG',
        payload: song
    }
}

Reducers

import { combineReducers } from 'redux'
const songReducer=()=>{
    return [
        {title: 'El Sawarekh ft. Zuksh & Shehta Karika – Ekhwaty' ,duration:'3:50'},
        {title: 'Sherine – Masha’er' ,duration:'4:00'},
        {title: 'Hala Al Turk – Zahgana' ,duration:'2:54'},
        {title: 'Hamza Namira – Dari Ya Alby' ,duration:'5:00'},
    ]
}

const selectedSongReducer=(selectedSong=null,action)=>{
    if(action.type==='SELECT_SONG'){
        return action.payload
    }
    return selectedSong
}

export default combineReducers({
    song:songReducer,
    selectedSong:selectedSongReducer
})

SongList.js

import React, { Component } from 'react'
import {connect} from 'react-redux'
class SongList extends Component {
    render() {
        console.log(this.props)   //First console  => undefined
        return (
            <div>SongList</div>
        )
    }
}

const mapStateToProps =state=>{
    console.log(state)              //Second console => Array(4)
    return {songs: state.songs}
}


export default connect(mapStateToProps)(SongList)

Solution

  • I don't see where SongList is called, with what props. I don't know Redux, but by any chance, you passed song without s inside combineReducers, maybe that is related.