Categories
React Answers

How to fix tests can’t fail within setImmediate or process.nextTick callback with React and Jest?

To fix tests can’t fail within setImmediate or process.nextTick callback with React and Jest, we can use await when we mount our component for testing.

For instance, we write

it("should render proper number of messages based on itemsPerPortion", async () => {
  const component = await shallow(
    <PublishedMessages
      itemsPerPortion={2}
      messagesStore={mockMessagesStore()}
    />
  );

  component.update(); // still needed
  expect(component.find(".item").length).toBe(2);
});

to mount the component PublishedMessages component with shallow.

We use await to wait for the next tick.

And then we call component.update to update the component and call expect to check our result.

Categories
React Answers

How to fix Excel file download being corrupted in React and Axios?

To fix Excel file download being corrupted in React and Axios, we set the responseType option when we make our Axios request to 'arrayBuffer'.

For instance, we write

import React, { Component } from "react";
import { saveAs } from "file-saver";

//...

const C = () => {
  const exportIssues = async () => {
    const response = await axios.get("/issues/export", {
      responseType: "arraybuffer",
    });

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    saveAs(blob, "file.xlsx");
  };

  //...
};

to create the exportIssues function that calls axios.get with the URL for the Excel file.

We set the responseType to 'arraybuffer' to download the file as a binary file.

And then we transform the response.data response data to a Blob with the Blob constructor.

And then we call saveAs with the returned blob and the file name for the file.

Categories
React Answers

How to make redirects after an axios post request with Express and React?

To make redirects after an axios post request with Express and React, we set window.location to the new URL value after the response from the axios request to the Express back end is available.

For instance, we write

import React, { Component } from "react";
//...

class MyClass extends Component {
  onSubmit = async (e) => {
    e.preventDefault();
    const { username, password } = this.state;
    const response = await axios.post("/login", { username, password });
    if (response.data.redirect == "/") {
      window.location = "/index";
    } else if (response.data.redirect == "/login") {
      window.location = "/login";
    }
  };
  //...
}
export default MyClass;

to create the onSubmit method that calls axios.post to make a POST request to the /login endpoint in our Express back end,

Then we get the response which has the redirect URL.

And then we set window.location to a new value to go to the URL.

Categories
React Answers

How to use history.push(‘path’) in react router 5.1.2 in a React stateful component?

To use history.push(‘path’) in react router 5.1.2 in a React stateful component, we call withRouter with our component so that the history prop is available in our component.

For instance, we write

import React, { Component } from "react";
import { withRouter } from "react-router-dom";

class MyClass extends Component {
  routingFunction = (param) => {
    this.props.history.push({
      pathname: `/target-path`,
      state: param,
    });
  };
  //...
}
export default withRouter(MyClass);

to create the routingFunction method that calls this.props.history.push with an object that redirects to pathname.

Categories
React Answers

How to pass the initial state while rendering a component with React?

To pass the initial state while rendering a component with React, we set the prop value as the value of the state’s initial value in getInitialState.

For instance, we write

class C extends Component {
  //...
  getInitialState() {
    return { foo: this.props.foo };
  }
  //...
}

to set the initial value of the foo state to the foo prop’s value.