Error message: Unable to assign type (Combining React, Typescript, and Firebase)

Just started using TypeScript and in the process of migrating my React app to incorporate it.

Encountering some type issues with Firebase auth service that I can't seem to find a solution for. Any suggestions?

import React, { useEffect, useState } from 'react';
import app from './firebase';

export const AuthContext = React.createContext(null);

export const AuthProvider: React.FC<Props> = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [pending, setPending] = useState(true);

  useEffect(() => {
    app.auth().onAuthStateChanged((user) => {
      // issue here
      setCurrentUser(user);
      setPending(false);
    });
  }, []);

  if(pending){
    return <>Loading...</>;
  }

  return (
    <AuthContext.Provider
      // issue here
      value={{ currentUser }}
    >
      {children}
    </AuthContext.Provider>
  );
};

interface Props {
  children: React.ReactNode;
}

setCurrentUser(user); is throwing an error stating

Argument of type 'User | null' is not assignable to parameter of type 'SetStateAction<null>'.

and

value={{ currentUser }} is showing an error as

Type '{ currentUser: null; }' is not assignable to type 'null'.

Answer №1

After retrieving the user parameter from firebase, it is important to note that its type cannot be assigned to null directly. To handle this situation, you can either create a custom type or interface for the user object, or simply use 'any' as a workaround:

const [currentUser, setCurrentUser] = useState<any>(null);

Answer №2

When I included to the environment, everything fell into place

export const AuthContext = createContext<any>(null)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage References in Material UI

I am attempting to utilize Refs in Material UI for updating Image src, but I am encountering an 'Undefined' error. It seems that the link is being generated but not applied as the Image src. My intuition tells me that the issue lies in line 10. ...

Unlimited API requests triggered by state changes within a callback

I am attempting to fetch data from an API and display it in a treeview using Material-UI. When the data is static, everything works perfectly fine. However, when I use the API in a callback function, it triggers an endless loop of calls... const getTreeIte ...

defining initial state values for a React class component using TypeScript

Here is the current state of the component: class Feed extends Component<FeedProps, FeedState> { constructor(props) { super(props); this.state = { isEditing: false, posts: [], totalPosts: 0, editPost: null, sta ...

Struggling to craft an accurate GraphQL request to Yelp

As a newcomer to Apollo, I am facing some challenges while trying to send a basic GraphQL query to the Yelp server. import React from 'react'; import { render } from 'react-dom'; import ApolloClient from 'apollo-boost'; impor ...

How do I maintain the Type<any> throughout my application state in NgRx without compromising on best practices?

Utilizing Angular 11.1.2 and rxjs 6.6.2 I am working on developing an application that dynamically displays a list of components. I have successfully achieved this functionality independently. However, I am currently encountering challenges when transitio ...

Tapping the image will redirect you to the corresponding component

My React Routes Challenge I've run into a roadblock while trying to implement react routes in my project. Greetings, everyone! This is my first time seeking help here, as I have previously posted about this issue on Codecademy. Below is the summary o ...

Using Material-UI in a project without the need for create-react-app

My objective is to utilize Material-UI without relying on create-react-app, as I feel that it abstracts too much and hinders my learning process. Unfortunately, all the instructions I have come across are centered around create-react-app. I am aiming to s ...

Leverage the `dispatch` hook within a useEffect function

When it comes to triggering an action upon the React component unmounting, I faced a challenge due to hooks not allowing the use of componentWillUnmount. In order to address this, I turned to the useEffect hook: const dispatch = useDispatch(); useEffect(( ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

`End session for inactive user after next authentication`

I am facing a challenge with managing inactive user sessions in my app. I tried setting the maxAge of ...nextauth to one minute and the refetch interval to 20s for SessionProvider, but encountered an issue where the session expiration on the browser cook ...

Building a Full-Stack Application with React, Express, and Passport

I'm in the process of setting up a full-stack application that utilizes React and Express JS. For authentication, I have implemented Passport.js but encountered a minor issue... My front-end and back-end are running as separate packages on different ...

React: detect the key pressed when submitting a form

I am currently working with React in combination with Material UI. My goal is to implement a functionality where the form submission only occurs when I click the Submit button, rather than triggering it by pressing enter while focused on a text field. Her ...

The React MUI Tree only shows updates when the user clicks on a child item

I have encountered an issue with my React MUI tree implementation. When I click on the "add" buttons to add a tree item, it gets added successfully to the ROMItems variable, but doesn't display immediately in the tree structure. The newly added item o ...

Troubleshooting issue with the spread operator and setState in React, Typescript, and Material-ui

I recently developed a custom Snackbar component in React with Material-ui and Typescript. While working on it, I encountered some confusion regarding the usage of spread operators and await functions. (Example available here: https://codesandbox.io/s/gift ...

Filter through the array of objects using the title key

I'm attempting to extract specific data by filtering the 'page_title' key. Below is a snippet of my JSON object: { "page_components": [ { "page_title": "My Account", "row_block": [ { "heading": "", "sub_headi ...

Any advice on dealing with authentication issues in React when using Firebase?

I am working on creating a user authentication page in react using firebase. I am able to sign in successfully, but the sign in button does not change to sign out after signing in. Can anyone help me diagnose the issue? const handleAuthentication ...

What sets usePreloadedQuery apart from useQueryLoader?

I've been exploring graphQL and the react-relay library. These are the key points I've covered: Rendering Queries: where usePreloadedQuery is introduced. Fetching Queries for Render: where useQueryLoader is introduced. To keep it simple, I&apo ...

Enhance your material-system experience with styled-components

I am currently utilizing the stack above to customize Material components using the props provided by the Material system in conjunction with styled-components. The component I am testing is as follows: import React from 'react' import Grid from ...

In React Router v6, you can now include a custom parameter in createBrowserRouter

Hey there! I'm currently diving into react router v6 and struggling to add custom params in the route object. Unfortunately, I haven't been able to find any examples of how to do it. const AdminRoutes: FunctionComponent = () => { const ...

Is there a way to rectify the issue where Auth::check() continues to return false despite being logged in?

I have a web app project where users can save their favorite websites. However, I am facing an issue where Auth::check() always returns false even when I am logged in as a user and trying to retrieve data through the API. I have one WebsiteController set ...