Ridiculously useful JS code snippets

Do you have a group of objects that you need to get data from but you can not count on the API to return the data consistently?

Try using an ID or some type of identifier and find what you need so that you can get the data that you want.

Consider the following examples:

const dataFromAPI = 
  {
    data: 
      [
        {
          id: 'data text', 
          value: 'Some data text'
        }, 
        {
          id: 'data numbers', 
          value: 1234
        }
      ]
  }

There is no effective way to reliably figure out how to get to ‘Some data text’ and using “magic numbers” (data[0].value) is never a good idea. So instead we can use some very concise javascript to find what we need.

const findIndex = (data, value) => {
  return data.findIndex(item => item.id === value)
}

// with above example code findIndex(dataFromAPI.data, 'data numbers') will return 1 (as this data set is located in the 1 position of the array)

Now we can effectively go and find the data that we want very easily while having confidence that as long as the API continues to return us the ID’s we will always be able to find what we want regardless of the order that the API returns data in.

return (
  datafromAPI.data[findIndex(datafromAPI.data, 'data text')].value
  ) // will return 'Some data text' from above data and example

Want to use Redux? Why bother when React has Context?

import React, { useState } from 'react'

const appContext = React.createContext()

const appContextProvider = ({ children }) => {
  const [hookState, setHookState] = useState({
    defaultValue: true, // set any defaults you want (language is a really common one to set)
    otherValue: false
}) // create the state

const updateHookState = (key, value) => {
  setHookState(prevState => ({
    ...prevState,
    [key]: value
  }))
} // allows us to update the state from anywhere and either update or add a new state value to be stored

return (
  < AppContext.Provider value={{ hookState, updateHookState }}>
    {children}
  < /AppContext.Provider>
)
}

export { AppContext, AppContextProvider } // export the provider and the context for setup and use across the app

October 21, 2021