Front end development

React Reducer Runs Twice

React Reducer Runs Twice

If using the react hook useReducer(reducer, state) and you notice it runs twice after dispatching an action - this is actually by design for development mode.

The reducer dispatches an action with a given state and returns a new state. It should never mutate the previous state.

If you follow this rule, you’ll never notice the reducer running twice. However if you are mutating the state and returning the new state based off that, you’ll make the mutation twice. So if you are adding something to a list in the state, you’ll see it added twice. This feature of react development keeps our functions pure. Pure functions are much easier to test.

React Hook Example: useState

React Hook Example: UseState

Below is an example of React hook useState to change the state of a boolean.


const MyCustomButton: React.FC<Props> = props => {
    // first argument defines the variable
    // second argument defines the funtion that changes the state
    // third - the assignment sets initial state
    const [open, setOpen] = React.useState<boolean>(false);

    return (
        <Button
        onClick={() => setOpen(true)}  // calls the function that will set the state
        >
    );
};

Axios Promise - Request and Response from the Client

Axios Promise - Request and Response From the Client

Simple example on how to send a post request from the client and handle the response.

Example

axios.post('/login', { firstName: 'Jack', lastName: 'Johnston' })
.then((response) => {
    // Success
  console.log(response);

}, (error) => {
    // Failure
  console.log(error);
});

Further Documentation

// Send a POST request
axios({
  method: 'post',
  url: '/user/new',
  data: {
    firstName: 'Joe',
    lastName: 'Smith'
  }
});

Install instructions

# NPM
npm install axios
-- or --
# Include Script Tag in JS file
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

Create A Service In Angular

Create a Service in Angular

To create a service in Angular:

cd /src/app/directory_to_create_service
ng generate service lookup 

To use service in a component inject into the constructor.

constructor(private lookupService: LookupService);
someMethod() {
    return this.lookupService.lookSomethingUp();
}