简体   繁体   English

如何最初调用 api 来保存帖子

[英]how to call the api initally to save the post

I want to save my snippet to the store.我想将我的代码段保存到商店。 However I'm facing some issues now, I only get the snippet id from the server after I have done the api call.但是我现在面临一些问题,在完成 api 调用后,我才从服务器获取片段 ID。 So the first time, I need to send only the snippetTile and snippetDescription to the api call.所以第一次,我只需要将snippetTile 和snippetDescription 发送到api 调用。 I want the snippetId to check whether a post already exist or not and to update it.我希望 snippetId 检查帖子是否已经存在并更新它。 How do I omit the snippetId in the api/savesnippets api call when I create a snippet for the first time?当我第一次创建片段时,如何在 api/savesnippets api 调用中省略片段 ID? I want only the snippetTitle and snippetDescription to be send to the api call as I will get the snippetId as the server response if everything goes well.我只想将snippetTitle 和snippetDescription 发送到api 调用,因为如果一切顺利,我将获得snippetId 作为服务器响应。 Right now my api call's request payload looks something like this .现在我的 api 调用的请求负载看起来像这样

codesandbox密码箱

actions.js where I call the api actions.js 我称之为 api

import { SAVE_POST, UPDATE_POST, RETRIEVE_POST, HOME_LOADED } from "./types";
import axios from "axios";
export const savePost = ({
  snippetId,
  snippetDescription,
  snippetTitle
}) => async dispatch => {
  const config = {
    headers: {
      "Content-Type": "application/json"
    }
  };
  let snippetData = { snippetId, snippetDescription, snippetTitle };
  try {
    if (snippetId == null) {
      const res = await axios.post(
        "/api/save",
        JSON.stringify(snippetData),
        config
      );
      snippetData.snippetId = res.data;  //cause I only get snippetId from the server
      dispatch({
        type: SAVE_POST,
        payload: snippetData
      });
    } else {
      await axios.post("/api/update", JSON.stringify(snippetData), config);
      dispatch({
        type: UPDATE_POST,
        payload: snippetData
      });
    }
  } catch (err) {
    console.log(err);
  }
};

editor.js编辑器.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { savePost, retrievePost } from "./actions/posts";

class Editor extends Component {
  constructor(props) {
    super(props);

    this.state = {
      title: "",
      enteredText: ""
    };
  }
  componentDidMount() {
    //Load the snippet
    retrievePost(this.props.match.params.snippetId);
  }

  // Save Snippet
  performSave = snippets => {
    console.log("save function clicked");
    const { enteredText, title } = this.state;
    this.props.savePost({
      snippetId: this.props.match.params.snippetId, //this should be null when initially I'm creating a new post
      snippetDescription: enteredText,
      snippetTitle: title
    });
  };
  render() {
    return (
      <>
        <input
          type="text"
          id="titletext"
          placeholder="Enter title here"
          limit-to="64"
          className="inptxt"
          onChange={title => this.setState({ title })}
        />
        <button className="btn savebtn" onClick={this.performSave}>
          Save Snippet
          <i className="fas fa-save" />
        </button>

        <textarea
          name="enteredText"
          onChange={enteredText => this.setState({ enteredText })}
        />
      </>
    );
  }
}

const mapStateToProps = state => ({
  snippets: state.snippets
});

export default connect(
  mapStateToProps,
  { savePost, retrievePost }
)(Editor);

reducer.js减速器.js

import {
  SAVE_POST,
  UPDATE_POST,
  RETRIEVE_POST,
  HOME_LOADED
} from "../actions/types";

import { initialState } from "../store";

export default function(state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case SAVE_POST:
      return {
        ...state,
        snippets: [payload, ...state.snippets] //this payload is only the snippetId right and not the actual snippet??
      };
    case UPDATE_POST:
      const newState = state.filter(
        post => post.snippetId !== payload.snippetId
      );
      return [...newState, payload];

    case RETRIEVE_POST:
      const newwState = state.filter(
        post => post.snippetId !== payload.snippetId
      );
      return [...newwState, payload];
    case HOME_LOADED:
      return {
        ...state,
        snippets: payload
      };
    default:
      return state;
  }
}

store.js store.js

import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import posts from "./reducers/posts";

export const initialState = {
  snippets: [
    {
      snippetId: "1",
      snippetTitle: "test",
      snippetDescription: "test test"
    },
    {
      snippetId: "2",
      snippetTitle: "post2",
      snippetDescription: "post 2 post2"
    }
  ]
};
const store = createStore(posts, applyMiddleware(thunk));
export default store;

Update Action.js更新Action.js

import { SAVE_POST, UPDATE_POST, RETRIEVE_POST, HOME_LOADED } from "./types";
import axios from "axios";
export const savePost = ({
  snippetId,
  snippetDescription,
  snippetTitle
}) => async dispatch => {
const config = {
headers: {
  "Content-Type": "application/json"
}
};

// remove snippetId here --------------------------------------
    let snippetData = { snippetDescription, snippetTitle };
// --------------------------------------

try {
 if (snippetId == null) {
  const res = await axios.post(
    "/api/save",
    JSON.stringify(snippetData),
    config
  );
  snippetData.snippetId = res.data;  //cause I only get snippetId from the server
  dispatch({
    type: SAVE_POST,
    payload: snippetData
  });
} else {

//add snippetId here for update use only --------------------------------------
  await axios.post("/api/update", JSON.stringify({...snippetData, snippetId}), config); 
// --------------------------------------
  dispatch({
    type: UPDATE_POST,
    payload: snippetData
  });
}
} catch (err) {
  console.log(err);
  }
};
// consider splitting your code with functions
const addToState = (state, action) => {
const cloneSnippets = JSON.stringify(JSON.parse(state.snippets)) // for deep copy
cloneSnippets.push(action.payload) // payload contains all the snipets info (id, descrip.., )
  return {
    ...state,
    snippets : cloneSnippets
  }
}

case SAVE_POST:
   return addToState(state, action)
}`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM