Answer the question
In order to leave comments, you need to log in
Why doesn't mapStateToProps output a value from an array?
Good afternoon :)
I ran into this problem:
There is a Weather component
import React from 'react'
import classes from './weather.module.css'
import {connect} from "react-redux";
class Weather extends React.Component {
render() {
return (
<div className={classes.weather}>
{this.props.other.city}
</div>
)
}
}
const mapStateToProps = (state) => {
debugger
return {
other: state.currentWeather.other
}
}
function mapDispatchToProps(dispatch) {
return null
}
export default connect(mapStateToProps, mapDispatchToProps)(Weather);
import {CURRENT_CITY, ADD_CITY} from "./actions/actionTypes";
const initialState = {
currentValue: '777',
other: [{
city: 'Gotham'
}],
}
export default function currentWeather(state = initialState, action) {
switch (action.type) {
case CURRENT_CITY:
return {
currentValue: action.payload
}
case ADD_CITY:
const addWeather = async () => {
const api_key = '0a18303f01a73e215e930966eb1a77bc'
const city = state.currentValue
const api_url = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${api_key}&units=metric`)
const data = await api_url.json()
if (data.cod == '400' || data.cod == '404') {
return null
}
initialState.other.push({
city: data.name,
country: data.sys.country,
temp: data.main.temp,
humidity: data.main.humidity,
wind: data.wind.speed,
feelsLike: data.main.feels_like
})
}
addWeather()
return {
currentValue: ''
}
default:
return state
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question