0

I'm a junior dev and have just joined recently. I'm trying to create a blog-like website where users can save a post and update an already saved post. I'm currently confused as to how to assign the snippetId within the post.

So this website was already made in Angular and I've been asked to migrate it to React. I'm mostly confused about how to store the ID as it is received from the server in response.data for a new post, and also, how I would receive it in the action.js file from the Redux store if it already exists.

Please help me understand the snippetData['snippetId'] part from the Angular and if I should I even use snippetData in the initialState or just use snippetId, snippetDescription, snippetTitle directly in the `initialState.

My code for now looks something like this:

action.js

import { SAVE_POST } from './types';

export const savePost=({snippetId, snippetDescription, snippetTitle})=> async dispatch=>{
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    }
}
const body = JSON.stringify({snippetId, snippetDescription, snippetTitle});
try{
    if(snippetId==null){
    const res = await axios.post('/api/save', body, config);
    dispatch({
        type: SAVE_POST,
        payload: res.data
    });}
    else{
        snippetData['snippetId']=snippetId
        const res = await axios.post('/api/update', body, config);
        dispatchEvent({
            type: UPDATE_POST,
            payload: res.data
        })
    }
}catch(err){
    console.log(err);
}

reducer/post.js

import { SAVE_POST} from '../actions/types';

const initialState={
    snippetData: {
        snippetId: null,
        snippetTitle: null,
        snippetDescription: null
    }
};

export default function (state=initialState, action){
    const {type, payload}=action;
    switch(type){
        case SAVE_POST:
            return {...state, 
            snippetData: {
                snippetId: payload,
                snippetDescription: payload,
                snippetTitle: payload}
        case UPDATE_POST: 
                return {...state,
                    snippetId: payload,
                    snippetDescription: payload,
                    snippetTitle: payload
                }
    }
}

This is finally the Angular file from where I've been asked to translate to React:

$scope.savesnippet=function(){
        $scope.snippetdata={}
        $scope.snippetdata['snippetTitle']=$scope.snippetTitle
        $scope.snippetdata['snippetDescription']=$scope.snippetDescription
        console.log($scope.snippetId)
        if($scope.snippetId==null){
            return $http.post('/api/save',$scope.snippetdata).then(function(response){
                if(response.status==200){
                    $scope.snippetId=response.data;
                    toaster.pop('success','Snippet saved successfully!')                    
                }else{                
                    toaster.pop('danger','An error has occured while saving the snippet. Please try again')                                        
                }
            });
        }else{
            $scope.snippetdata['snippetId']=$scope.snippetId        
            return $http.post('/api/update',$scope.snippetdata).then(function(response,status){
                if(response.status==200){
                    toaster.pop('success','Snippet saved successfully!')                                        
                }else{
                    toaster.pop('danger','An error has occured while updating the snippet. Please try again')                                                            
                }
            });
        }
    }

edit:

editor.js

performSave = (snippetData) => {

    const {enteredText, title} =  this.state;
    let {snippetId, snippetDescription, snippetTitle} = snippetData;

    snippetTitle=title;
    snippetDescription=enteredText;
    savePost(snippetId, snippetDescription, snippetTitle);
    }

const mapStateToProps = state=>({
  snippetData: state.snippetData
})

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

4
  • 1
    Here snippetData['snippetId'] represent that u are creating a new post of updating a post. If it present, meaning update. else creating new post Commented Mar 25, 2020 at 15:37
  • how do I declare snippetData['snippetId'] in the action file. it will be undefined right? I'm very confused regarding the snippetData and snippetId Commented Mar 25, 2020 at 15:38
  • 1
    u actually dont need to define it. U can pass the value along the payload. if you update same post. u have the value already. let me add a sample code. Commented Mar 25, 2020 at 15:39
  • please check! updated code Commented Mar 25, 2020 at 15:47

1 Answer 1

1

What i understand from you given angular code, on API save success, you dont get entire data. U only get id of the save data. So in payload you need to update snippetId. In case of save success, you dont need any update. U can just use as payload.

import { SAVE_POST } from "./types";

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
      dispatch({
        type: SAVE_POST,
        payload: snippetData
      });
    } else {
      const res = await axios.post("/api/update", JSON.stringify(snippetData), config);
      dispatchEvent({
        type: UPDATE_POST,
        payload: snippetData
      });
    }
  } catch (err) {
    console.log(err);
  }
};

// Reducer:

import { SAVE_POST } from "../actions/types";

const initialState = {
  snippetData: {
    snippetId: null,
    snippetTitle: null,
    snippetDescription: null
  }
};

export default function(state = initialState, action) {
  const { type, payload } = action;
  switch (type) {
    case SAVE_POST:
      return {
        ...state,
        snippetData: payload
      };
    case UPDATE_POST:
      return {
        ...state,
        snippetData: payload
      };
  }
}
Sign up to request clarification or add additional context in comments.

7 Comments

yeah, correct. on succesful post request, we just get an Id from the server and on update api success, just get a text message that updated. the reducers/post.js file is correct or is there any adjustments to be made there too? specially in the return statements?
are you talking about the reducer file? i dont see it
no here. snippetData.snippetId = res.data if (snippetId == null) { const res = await axios.post("/api/save", JSON.stringify(snippetData), config); snippetData.snippetId = res.data dispatch({ type: SAVE_POST, payload: snippetData }); }
yeah i get it. this is the action file. I'm asking if my reducer/post.js file is correct or not as you can check in my question, I added the reducer code too there..
thanks for the help, I'll check and accept it as answer if it works.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.