Categories
React

How to make queries with React Query?

The React Query library lets us make HTTP requests easily in our React apps.

In this article, we’ll look at how to to make queries with React Query

How to make queries with React Query?

Query functions are functions that returns a promise and it’s passed into the 2nd argument of the useQuery hook.

For instance, we can write:

index.js

import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "react-query";
import App from "./App";

const queryClient = new QueryClient();

const rootElement = document.getElementById("root");
ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <StrictMode>
      <App />
    </StrictMode>
  </QueryClientProvider>,
  rootElement
);

App.js

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { data } = useQuery("yesNo", () => axios("https://yesno.wtf/api"));

  return <div>{JSON.stringify(data)}</div>;
}

to return the promise return by the axios function.

The returned promises’ data will be set as the value of the data property.

Handling and Throwing Errors

React Query expects that an error is thrown in the query function when an error occurred.

If it doesn’t then we’ve to throw it ourselves.

For instance, we can write:

import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { error } = useQuery("todo", async () => {
    const response = await fetch(
      "https://jsonplaceholder.typicode.com/posts/100000000000"
    );
    if (!response.ok) {
      throw new Error("Network response was not ok");
    }
    return response.json();
  });

  return <div>{error && error.message}</div>;
}

If we use the Fetch API to make HTTP requests, then we’ve to check whether the response.ok property is true .

If it’s not, then we’ve to throw an error to let React Query know that an error has occurred.

This has to be done since fetch doesn’t throw an error when we get a non-200 series response.

If response.ok is true , we return the response by calling response.json() .

Query Object

We can pass in a query object instead of pass in every as separate arguments to make our GET request.

For instance, we can write:

import axios from "axios";
import React from "react";
import { useQuery } from "react-query";
export default function App() {
  const { data } = useQuery({
    queryKey: ["todo", 1],
    queryFn: ({ queryKey: [, id] }) => {
      return axios(`https://jsonplaceholder.typicode.com/posts/${id}`);
    }
  });

  return <div>{JSON.stringify(data)}</div>;
}

queryKey has the identifier of the request.

queryFn is the function for making the request.

Conclusion

We can pass in functions that returns a promise to make requests to the useQuery hook to make GET requests with React.

Categories
React Answers

How to Update a React Context from Inside a Child Component?

To update a React Context from inside a child component, we can wrap the React Context provider around the child components.

Then we set the value prop of the context provider to the the state setter function that lets us update the context value.

Then we can use the useContext hook to access the context.

For instance, we write:

import React, { useContext, useState } from "react";

const Context = React.createContext();

const Foo = () => {
  const [, setVal] = useContext(Context);

  return (
    <div>
      <button onClick={() => setVal("foo")}>foo</button>
    </div>
  );
};

const Bar = () => {
  const [, setVal] = useContext(Context);

  return (
    <div>
      <button onClick={() => setVal("bar")}>bar</button>
    </div>
  );
};

export default function App() {
  const [val, setVal] = useState();

  return (
    <Context.Provider value={[val, setVal]}>
      <Foo />
      <Bar />
      <p>{val}</p>
    </Context.Provider>
  );
}

to create the Context context with the React.createContext method.

Next, we create the Foo component which calls the useContext hook with Context to return the value of its value prop.

In both Foo and Bar, we call setVal to set the value of val`.

val and setVal are passed down from the array we set as the value of the value prop of Context.Provider.

Since Foo and Bar are inside Context.Provider we can access the context’s value prop value with useContext.

Therefore, when we click the buttons, we see the val value in App change.

Categories
React Answers

How to Fix the ‘React eslint error missing in props validation’ When Developing a React App?

Sometimes, we run into the ‘React eslint error missing in props validation’ when developing a React app.

In this article, we’ll look at how to fix the ‘React eslint error missing in props validation’ when developing a React app.

Fix the ‘React eslint error missing in props validation’ When Developing a React App?

To fix the ‘React eslint error missing in props validation’ when developing a React app, we can set the prop types of the props in the component causing the error.

For instance, we write:

import React from "react";
import PropTypes from "prop-types";

const Foo = ({ someProp, onClick }) => {
  return <div onClick={onClick}>foo {someProp}</div>;
};

Foo.propTypes = {
  someProp: PropTypes.number.isRequired,
  onClick: PropTypes.func.isRequired
};

export default function App() {
  const onClick = () => console.log("clicked");

  return <Foo someProp={2} onClick={onClick} />;
}

to import the prop-types package to let us add prop type validation to the Foo component.

We install it by running:

npm i prop-types

We set the Foo.propTypes property to an object that has the prop names as the keys and the corresponding prop types as the values.

So someProp is a number and it’s required.

And onClick is a function and it’s also required.

Then in App, we render the Foo component with the props passed in.

Now we won’t get any errors from ESLint.

Conclusion

To fix the ‘React eslint error missing in props validation’ when developing a React app, we can set the prop types of the props in the component causing the error.

Categories
React Answers

How to Fix the ‘”JSX not allowed in files with extension ‘ .js'” Error with eslint-config-airbnb When Developing a React App?

Sometimes, we want to fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb when developing a React app.

In this article, we’ll look at how to fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb when developing a React app.

Fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb When Developing a React App

To fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb when developing a React app, we can add the "react/jsx-filename-extension" to allow files with the .js extension to include JSX code in our .eslintrc file.

To do this, we write:

"rules": {
  "react/jsx-filename-extension": [1, { "extensions": [".js", ".jsx"] }],
}

to allow JSX code to be added to files with the .js and .jsx extensions.

Conclusion

To fix the ‘"JSX not allowed in files with extension ‘ .js’" Error with eslint-config-airbnb when developing a React app, we can add the "react/jsx-filename-extension" to allow files with the .js extension to include JSX code in our .eslintrc file.

Categories
React Answers

How to Get the Height of an Element with React?

Sometimes, we want to get the height of an element with React.

In this article, we’ll look at how to get the height of an element with React.

Get the Height of an Element with React

To get the height of an element with React, we can assign a ref to the element we want to get the height for.

Then we can use the clientHeight property to get the height.

For instance, we write:

import React, { useRef } from "react";

export default function App() {
  const elementRef = useRef(null);
  console.log(elementRef.current?.clientHeight);

  return <div ref={elementRef}>hello world</div>;
}

We call the useRef hook and assign the returned ref to elementRef.

Then we set elementRef as the value of the ref prop of the div.

Finally, we log the height of the div by logging elementRef.current?.clientHeight.

Therefore, we should see 18 logged, which is the height of the div in pixels.

Conclusion

To get the height of an element with React, we can assign a ref to the element we want to get the height for.

Then we can use the clientHeight property to get the height.