Я пытаюсь установить состояние профиля через Redux.Однако по какой-то причине мой axios вызывается дважды
моя база данных profile.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
preference: [
{
type: String
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Profile = mongoose.model("profile", ProfileSchema);
myCreatePreferences class
import React, { Component } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import checkboxes from "./checkboxes";
import Checkbox from "./Checkbox";
import axios from "axios";
import { Redirect } from "react-router";
import { withRouter } from "react-router-dom";
import Select from "react-select";
import { getCurrentProfile } from "../../actions/profileActions";
const options = [
{ value: "Guns", label: "Guns" },
{ value: "Gay Marriage", label: "Gay Marriage" },
{ value: "Abortion", label: "Abortion" },
{ value: "IT", label: "IT" }
];
class CreatePreferences extends Component {
constructor() {
super();
this.state = {
selectedOption: [],
fireRedirect: false
};
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
e.preventDefault();
let tempArray = [];
for (let i = 0; i < this.state.selectedOption.length; i++) {
tempArray[i] = this.state.selectedOption[i].value;
}
const preference = {
tempArray
};
//axios
// .post("/api/profile/", { tempArray: tempArray })
//.then(res => res.data)
// .catch(err => console.log(err));
this.props.getCurrentProfile(preference);
this.setState({ fireRedirect: true });
}
handleChange = selectedOption => {
this.setState({ selectedOption });
console.log(`Option selected:`, selectedOption);
};
render() {
const { selectedOption } = this.state;
console.log(selectedOption.value);
const { fireRedirect } = this.state;
return (
<div>
<form onSubmit={this.onSubmit}>
<Select
value={selectedOption}
isMulti
onChange={this.handleChange}
options={options}
/>
<input
type="submit"
className="btn btn-info btn-block mt-4"
value="Save Preferences"
/>
{fireRedirect && <Redirect to={"/"} />}
</form>
</div>
);
}
}
CreatePreferences.propTypes = {
profile: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
profile: state.profile
});
export default connect(
mapStateToProps,
{ getCurrentProfile }
)(withRouter(CreatePreferences));
мой профильActionsclass
import axios from "axios";
import {
GET_PROFILE,
PROFILE_LOADING,
GET_ERRORS,
CLEAR_CURRENT_PROFILE
} from "./types";
//Get current profile
export const getCurrentProfile = preference => dispatch => {
dispatch(setProfileLoading());
axios
.post("/api/profile", preference)
.then(res =>
dispatch({
type: GET_PROFILE,
payload: res.data
})
)
.catch(err =>
dispatch({
type: GET_PROFILE,
payload: { err }
})
);
};
//Profile Loading
export const setProfileLoading = () => {
return {
type: PROFILE_LOADING
};
};
//Clear Profile
export const clearCurrentProfile = () => {
return {
type: CLEAR_CURRENT_PROFILE
};
};
profileReducer.js
import {
GET_PROFILE,
PROFILE_LOADING,
CLEAR_CURRENT_PROFILE
} from "../actions/types";
const initialState = {
profile: null,
profiles: null,
loading: false
};
export default function(state = initialState, action) {
switch (action.type) {
case PROFILE_LOADING:
return {
...state,
loading: true
};
case GET_PROFILE:
return {
...state,
profile: action.payload,
loading: false
};
case CLEAR_CURRENT_PROFILE:
return {
...state,
profile: null
};
default:
return state;
}
}
Хранилище редуксов класса index.js.
import { combineReducers } from "redux";
import authReducer from "./authReducer";
import errorReducer from "./errorReducer";
import profileReducer from "./profileReducer";
import postReducer from "./postReducer";
export default combineReducers({
auth: authReducer,
errors: errorReducer,
profile: profileReducer,
post: postReducer
});
Когда я отправляю данные из класса createPreference через profileActions через axios, я получаю два сообщения axiosзапрос.Сначала он заполняет предпочтение, как и ожидалось, однако мгновенно выполняет другой вызов, и предпочтение снова устанавливается равным null. Console.log (для вызова)
preference: Array(2), _id: "5bbc73011f67820748fcd9ab", user: "5bb87db33cb39a844f0ea46a", date: "2018-10-09T09:21:05.968Z", __v: 0}
Dashboard.js:20 {preference: null, _id: "5bbc73011f67820748fcd9ab", user: "5bb87db33cb39a844f0ea46a", date: "2018-10-09T09:21:05.968Z", __v: 0}
Есть предложения о том, как это исправить?