Answer the question
In order to leave comments, you need to log in
How to make a request to the server in an action and store the value?
Greetings) I'm learning react / redux, and I'm completely confused (((
There is a CatalogAction.js
//action
const getProducts = id => {
console.log(id); // выводит id
return dispatch => {
dispatch({
type: GET_PRODUCTS_REQUEST,
payload: {
wait: true
}
});
};
};
dispatch({
type: GET_PRODUCTS_SUCCESS,
payload: {
wait: true
product: data // ответ от сервера записать сюда
}
const initialState = {
wait: false,
products: {
a: "апельсин",
b: "яблоко",
c: "банан"
}
};
export function catalogR(state = initialState, action) {
switch (action.type) {
case GET_PRODUCTS_REQUEST:
return {
...state,
wait: action.payload.wait
};
case GET_PRODUCTS_SUCCESS:
return {
...state,
wait: action.payload.wait,
products: action.payload.products
};
default:
return state;
}
}
import { createStore, applyMiddleware } from "redux";
import { rootReducer } from "../reducers/rootReducer";
import thunk from "redux-thunk";
import logger from "redux-logger";
export const store = createStore(rootReducer, applyMiddleware(thunk, logger));
import React, { Component } from "react";
import { connect } from "react-redux";
import CatalogNav from "../../components/content/CatalogPage/Catalog/CatalogNav/CatalogNav";
import getProducts from "../../actions/CatalogAction";
class CatalogNavContainer extends Component {
render() {
return (
<div className="CatalogNavContainer">
<CatalogNav getProducts={this.props.getProducts} />
</div>
);
}
}
// приклеиваем данные из store
const mapStateToProps = store => {
return {
c: null
};
};
const mapDispatchToProps = dispatch => {
return {
getProducts: year => dispatch(getProducts(year))
};
};
// в наш компонент App, с помощью connect(mapStateToProps)
export default connect(
mapStateToProps,
mapDispatchToProps
)(CatalogNavContainer);
Answer the question
In order to leave comments, you need to log in
const getProducts = id => {
console.log(id); // выводит id
dispatch({
type: GET_PRODUCTS_REQUEST,
payload: {
wait: true
}
});
return dispatch => {
fetch(`/backend/${id}.json`)
.then(
response => dispatch({
type: GET_PRODUCTS_SUCCESS,
payload: {
wait: false,
products: response.json()
}
})
)
};
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question