Skip to content

Instantly share code, notes, and snippets.

@clalexni
Forked from jsnwesson/001 - Journal Homepage.md
Last active March 28, 2022 23:48
Show Gist options
  • Save clalexni/7c6dec230b6bd54c9303cb9c5e81c51a to your computer and use it in GitHub Desktop.
Save clalexni/7c6dec230b6bd54c9303cb9c5e81c51a to your computer and use it in GitHub Desktop.
Catwalk Engineering Journal

2021-10-27 Learn Redux

Overview

  • Learn Redux carefully and take notes.
  • Redo previous redux sprints
  • watched "intro to redux" and the solution video.
  • @fredx (Fred Zirdung) is an awesome lecturer. Sad to know that he left HR.
  • learned about "component-connect-store" 3 layers architechture in Redux.. it's beautiful!

Resources

Why Redux?

  • predictable state container for JS app

    • centralized state (one single state container)
    • seperate state logic from components (avoids tight coupling)
  • predicatable flow of pure functions (?)

Redux Principles:

  • enforce unidirectional updates (?)
  • allow easy scaling based on feature

3 Components of Redux: store, action and reduer

  • store (an object with these 3 useful methods and more)

    • getState
    • dispatch: tells state to update
    • subscribe: registers functions to be invoked when state updates
      • the react component subscribe to the store with a function (listener)
      • the function is responsible to update react component (rerender)
        • the function needs to call setState (?) to trigger rerender
      • the store will invoke all listeners when state changes
  • action (describe intention to change state)

    • an object with a type key(with its value string) and data (payload)
    • an argument to dispatch
      • action is created outside the store (in react component)
      • dispatch is invoked with action (also by the react componenet)
    • ONLY way to get data into store
  • reducer

    • function that take state and action as arguments and return a new state
    • should not mutate state but instead make a new state
    • in practice you will combine multiple reducers into one root reducer
      • each small reducer will only take and return partial state

example

  • after a click...
    • event handler function in react is passed down from App
    • that handler function in Redux will instead be creating an action and invoke dispatch
var initialState = {
  nominees: [
    {
      name: 'React',
      votes: 0
    },
    {
      name: 'Angular',
      votes: 0
    },
    {
      name: 'Vue',
      votes: 0
    }
  ]
};

// simple reducer that takes the entire state and return new whole state
const reducer = (previousState, action) => {
  if (previousState === undefined) {
    // reducers must handle this case
    previousState = initialState;
  }
  if (action.type === 'VOTE') {
    const newState = {};
    const newNominees = previousState.nominees.map(nominee => {
      if (nominee.name === action.payload) {
        return {
          name: nominee.name,
          votes: nominee.votes + 1
        }
      } else {
        return nominee;
      }
    });
    newState.nominees = newNominees;
    return newState;
  } else {
    return previousState;
  }
}

// create store
const store = Redux.createStore(reducer);

// revoke dispatch
// provide action to dispatch
store.dispatch({type: 'VOTE', payload: 'React'})

// subscribe
store.subscribe(() => { console.log('state changedi:', store.getState()); });

2021-10-28 Architect

Overview

  • at this point I understood 95% of Redux excepts hooks
  • Architechtural design, organize the files.
  • Design redux states.

Architechtural design

  • previously I had actions, containers, componenets, store, reducers all on the same hiearchy level
  • changed design after studying this design pattern
    • instead each compoenets are at a same hiearchy
      • each component has it own action, reducer and type (action type)
    • easier for others to understand and reason about what's going on (better for group project)
    • helps visualize redux state and partial state for each reducer
    • each person's reponsibility is more clear

Redux state design rough draft

{
  currentItemIndex: null, //

  overview: {
    styleList: [],
    currentStyle: styleId,

  },

  qa: {
    questionList: [],
    answerList: []
  },

  ratingAndREview: {
    ratingList: [],
    rating:
  },

  relatedItems: {
    itemList: [id1, id2, id3]
  }
}

2021-10-29 Apply Redux, design API routes

Overview

  • redux state design change
  • implement redux
    • also saw the state and state changes using "Redux Dev" on Chrome, it's sick
  • design and implement server API routes

design change in state and implement redux

  • realized that all 4 widgets depend on a single product id
  • need to fetch product list before anything else in order to get the default product id
{
  currentProduct: null,
  productList: [],
  overview: {
  },
  qa: {
  },
  ratingAndReview: {
  }
}
  • made currentProduct and productList a top level property in the redux state
  • still havent consider what to store in each widget
  • implemented redux and got productList and currentProduct working, good progress

design and implement server API routes

const router = require('express').Router();
var config = {
  headers : {
    'Authorization': API_KEY
  }
};

router.get('/questions/productId/:product_id', (req, res) => {
  let params = {
    product_id: req.params.product_id,
    page: req.query.page || '1',  // default value
    count: req.query.count || '5' // default value
  };

  axios.get(url, {...config, params: params})
    .then(response => {
      res.status(200).send(response.data);
    })
    .catch(err => {
      console.error(err);
      res.status(400).send();
    })
});

2021-10-30 Think through the problem

Overview

  • Calm down and think before you start typing, Alex
  • What are needed to be done in order to do things effectively?
    • study everyone's API routes and not just my own
    • high overview and deep understand of what everyone's needs are
    • useful for state design

Investigate

  • bundle thunks together for better performance possibly
    • how? => start fetching critical data (not just product list) before DOM render
    • potential problem => loading vs isLoaded issue (async)
      • need to take it under consideration in state design

Think through the problem

  • what are everyone's need? (study the api)

Product

Index Description goal/Note
1 get product list product id
2 get product of an id features of each product id
3 get styles of an id style list each style id has multiple size (each has an sku id)
4 get related products of an id list of product id

Reviews

Index Description Goal/Note
1 get detail review list of a product id show review details & responsesi (no characteristics)
2 get review meta of a product id ratings counts overviewi & chariacteristics (sise, comfort...) breakdown
3 add review for a product id can specify characteristic id and its value
4 mark review helpful for review id
5 report reivew for review id

QA

Index Description Goal/Note
1 get questions list questions & answers for all product (exhausive)(also can specify a product id
2 get answer list for a question id Not needed
3 add question for a product id if success fetch and update question list
4 add answer for a question id ``
5 mark question helpful for question id ``
6 report question for question id ``
7 mark answer helpful for answer id ``
8 report answer for answer id

Cart

Index Description Goal/Note
1 get cart items sku id and count
2 add to cart for a sku id do post then update cart list

State

{
  currentProductId: NaN, // or 0, null?

  productList: {
                products: [], // desc, caterory, and slogan for all products
                loading: false
               },

  styleListForCurrentProduct: {
                                styles: [],
                                loading: false
                              },
                                    
  currentProduct: {
                    product: null, // with feature list of the product
                    loading: false
                  },

  relatedProductsForCurrentProduct: {
                                      products: [], // not needed for now
                                      loading: false
                                    },
  reviewListForCurrentProduct: {
                                reviews: [],
                                loading: false
                               },
  reviewMetaForCurrentProduct: {
                                meta: null, // for characteristic breakdown
                                loading: false
                               },

    // qa-1 API
  questionListForCurrentProduct : {
                                    questions: [],
                                    loading: false
                                  },
    
  
  cart: {
    items: [], // add in cart when post request is successful
  }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment