Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  5] [ 3]  / answers: 1 / hits: 10838  / 4 Years ago, tue, may 5, 2020, 12:00:00

I have a situation where i can successfully dispatch my states with reducers and i can render it in my component



Here the relevant code



in my action/index.js



export const receivedLeaguesList = json => ({
type: RECEIVE_LEAGUES_LIST,
json: json
});

export function fetchLeaguesList() {
return function(dispatch) {
dispatch(requestLeaguesList());
return axios
.get(https://www.api-football.com/demo/v2/leagues/)
.then(res => {
let leagues = res.data.api.leagues;
dispatch(receivedLeaguesList(leagues));
})
.catch(e => {
console.log(e);
});
}
}


my reducers/index.js



import { REQUEST_LEAGUES_LIST, RECEIVE_LEAGUES_LIST } from ../actions;

const initialState = {
leaguesList: [],
isLeagueListLoading: false
};

const reducer = (state = initialState, action) => {
switch (action.type) {
case REQUEST_LEAGUES_LIST:
return { ...state, isLeagueListLoading: true };
case RECEIVE_LEAGUES_LIST:
return { ...state, leaguesList: action.json, isLeagueListLoading: false };
default:
return state;
}
};


in my component component/Leagues.js



let Leagues = ({ leaguesList, loading, getList }) => {
useEffect(() => {
getList();
}, [getList]);


const [itemsLeagues] = useState([leaguesList]);

console.log(league list, itemsLeagues);

const mapDispatchToProps = {
getList: fetchLeaguesList
};


I have reproduced the demo here => https://codesandbox.io/s/select-demo-71u7h?



I can render my leaguesList states in my component doing the map, but why when



  const [itemsLeagues] = useState([leaguesList]);

console.log(league list, itemsLeagues);


returns an empty array ?



See the imageenter


More From » reactjs

 Answers
4

You're setting useState's init value wrong:



 const [itemsLeagues] = useState(leaguesList);


instead of



 const [itemsLeagues] = useState([leaguesList]);


The return value of useState isn't the value itself, but the array of value and mutator:



const [value, setValue] = useState([42, 43])
// here's value equals [42, 43]


So if you were trying to destructure the wrapping array you passed to useState(), you should use it like this (though you don't need it):



const [[itemsLeagues]] = useState([leaguesList]);

[#3913] Sunday, May 3, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadyngraysons

Total Points: 455
Total Questions: 109
Total Answers: 98

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
jadyngraysons questions
Thu, Apr 23, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
Tue, Dec 31, 19, 00:00, 4 Years ago
Wed, Dec 11, 19, 00:00, 5 Years ago
;