My error occurs when I try to send api requests with axios but do not see the same error sending the request with fetch. I looked at several react-native applications and It looks like I am using the axios.get method similar to theirs and don't see what I am doing wrong. I am new to react native so maybe I am doing something naively.
import React from 'react'
import {
View,
Button
} from 'react-native'
import axios from 'axios'
const Example = () => {
const requestGoogle = () => {
const url = 'https://google.com'
axios.get(url) //fetch(url) no error
.then(res => {
alert(res)
})
.catch(err => {
alert(err)
})
}
return ( <
View >
<
Button title = "Send"
onPress = {
() => requestGoogle()
}
/> <
/View>
);
}
export default Example
I get the following error when running the previous code:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
Looking into each reason:
I confirmed that React and React Dom have same react version 16.13.1
I don't think I but maybe?
I confirmed that only one copy of app exists in the project following their steps
Related
I am making a simple program with a backend in ASP.NET Core Web API, and a frontend in JS React. I have a SQL-database in my backend with a table called Events (Arrangementer in Norwegian). The events table has three columns: ID, name, and description.
I have opened and started the react-project. In my App.js (which is the only file I have edited since opening the project), I am trying to fetch some event data from my SQL-database. When I try to console.log() the json-response, nothing gets outputted to the console. I have tried using an ASYNC function, but that doesnt work either. My backend is up and running, and I have data inside of the tables, i can see that when i click the fetch-url.
Here is the App.js file:
import logo from './logo.svg';
import './App.css';
import {useEffect, useState} from 'react'
function App() {
useEffect(() => {
fetch("https://localhost:7031/api/Arrangements")
.then((res) => res.json())
.then((json) => {
console.log(json)
})
}, [])
return (
<div className="App">
<header className="App-header">
testing project
</header>
</div>
);
}
export default App;
The getter in the Swagger UI
I believe something is wrong with the endpoint. First thing that strikes me is that the url you are using starts with https:// but adresses localhost. I'm aware that's possible, but are you sure it's not http:// ?
To be sure of that, please test your endpoint using Postman or the Chrome Dev tools network tab - both should give you sufficient information about the status of your endpoint.
Your frontend code looks good and should work, so I believe you have a backend problem.
Try it plz. Seems your code is fine. If your get response from Backhand(200 in Network Tab) no issues.
import React from 'react';
import { useState,useEffect } from 'react';
const MyApp = () => {
const [service, setService] = useState({})/According to Your API response;
useEffect(() => {
const url = "http://localhost:7031/api/Arrangements";
fetch(url)
.then(res =>res.json())
.then(data => setService(data));
}, [])
return (
<div>
<p>{service.length}</p>
</div>
);
};
export default MyApp;
If you console log the res, you will see some response.
But I don't think you can use JSON in the last .then, because res.json() doesn't save your data anywhere.
Try using a useState, and set that state in the last .then.
I got the below errors while building my application. Not sure why this is happening. I wrote a fetch in a sperate function and my trying to call my fetch function (that is styled as a custom react hook) in my getStaticSite props but it is not letting me. How can I bypass this problem? I don't think I'd have this problem if I just wrote the fetch directly into the getStaticSite props, but for organizational reasons I prefer to write my fetches in functions.
The Error I get:
./pages/SSG/paristimeisg.js
6:22 Error: React Hook "useFetchParisTimeISG" is called in function "getStaticProps" that is neither a React
function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use". react-hooks/rules-of-hooks
useFetchParisTimeISG code below
import React from "react";
export default async function useFetchParisTimeISG() {
const response = await fetch(
`https://timeapi.io/api/Time/current/zone?timeZone=Europe/Paris`
);
const currenttimeinparis = await response.json();
return currenttimeinparis;
}
paristimeisg page code below.
import useFetchParisTimeISG from "../../hooks/SSR/ISR/useFetchParisTimeISG";
export async function getStaticProps() {
let mytime = await useFetchParisTimeISG();
return { props: { mytime }, revalidate: 60 };
}
export default function paristimeisg({ mytime }) {
console.log("This is my time", mytime);
return (
<div>
Hello
<h2>{mytime.milliSeconds}</h2>
</div>
);
}
Extra question
I get the same error listed as the above for this page, despite not having any react hooks inside non react components(unless I am missing something?).
Error I get:
./pages/SSG/timeforISG.js
5:16 Error: React Hook "useFetchParisTimeISG" is called in function "timeforISG" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use". react-hooks/rules-of-hooks
Page code
import React from "react";
import useFetchParisTimeISG from "../../hooks/SSR/ISR/useFetchParisTimeISG";
export default function timeforISG() {
let mytime = useFetchParisTimeISG();
return <div>{mytime}</div>;
}
useFetchParisTimeISG code is the same as above (top of page).
Your issue is a simple one - you are incorrectly trying to use a React Hook in a non-React component (getStaticProps, which is a NextJS function).
The solution is simple:
Create a plain old JavaScript file that is not named like a Hook (e.g. parisTimeFetcher.js)
Paste in your original code (with a function name change to avoid a possible React error over the "use" syntax, and remove the React import as it is just plain JavaScript):
export default async function fetchParisTimeISG() {
const response = await fetch(
`https://timeapi.io/api/Time/current/zone?timeZone=Europe/Paris`
);
const currenttimeinparis = await response.json();
return currenttimeinparis;
}
Now, import the function into your Next page, and use this function inside getStaticProps:
import { fetchParisTimeISG } from "../../fetchers/parisTimeFetcher";
export async function getStaticProps() {
let mytime = await fetchParisTimeISG();
return { props: { mytime }, revalidate: 60 };
}
Giving your naming that is prefixed with use, React assumes that you're trying to call a hook with its manageable state outside of a component (which it will not work) thats why it throws this error.
Hooks shouldn't be called inside a regular functions as mentionned in react official Doc
You should change your naming and remove the use Prefix (You dont have to remove it from the the file name but its recommended)
I have this custom hook to get the current user from firebase:
import React, { Component, useEffect, useState } from 'react';
import { auth } from "../firebase/auth-service"
const useFirebaseAuthentication = (firebase) => {
const [authUser, setAuthUser] = useState(null);
try {
auth.onAuthStateChanged(async user => {
if (user) {
setAuthUser(user)
} else {
setAuthUser(null);
}
})
} catch (error) {
throw error
}
return authUser
}
export default useFirebaseAuthentication;
When I print on the screen the current user from this custom hook - I get the result as expected.
When I use the hook and try to get the user - I get null.
Can someone point out my mistake?
I don't think that useState here is appropriate, don't you get any console warnings? A hook is just a js function as any other, it's not a React component!
Try to use a local variable instead...
edit
useState is a hook, therefore you should be getting this warning:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See for tips about how to debug and fix this problem.
It's exactly what's a problem here: you use a hook NOT inside the body of a react functional component, you use it in an ordinary js function.
I'm trying to use responsive javascript media queries using useMediaQuery however I can't get it to work, I get: -
Error message:
"useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
Playground
https://stackblitz.com/edit/react-ts-5vseqr?file=media-query.ts
I think it's erroring on line 4 of media-query.ts
import { useState, useEffect } from 'react'
const useMediaQuery = (query: string) => {
const [match, setMatch] = useState(false)
useEffect(() => {
const updateMatch = () => setMatch(window.matchMedia(query).matches)
updateMatch()
window.matchMedia(query).addEventListener('change', updateMatch)
return () => {
window.matchMedia(query).removeEventListener('change', updateMatch)
}
}, [query])
return match
}
export default useMediaQuery
What you've done here is writing a custom hook(useMediaQuery). You've done that properly so no issues there. Above code snipped is fine.
The problem is in the index.tsx file when you try to use the above custom hook that you've written. As the error suggests your custom hook is called outside the react component there in line 7 of index.tsx.
You have to move the useMediaQuery call inside the App component. Also currently your App component is a class component which you have to convert to a functional component to use hooks inside it.
here's the adjusted code:
https://stackblitz.com/edit/react-ts-m6rwpd?file=index.tsx
I get an error in the console as
error!! [Error: Invalid hook call. Hooks can only be called inside of
the body of a function component. This could happen for one of the
following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app*
import firebase from '../../database/firebase';
import { useDispatch } from 'react-redux';
import * as actions from "../../store/actions";
export const userProfilePcture =(id)=>{
const image = firebase.storage().ref(id + '/profilePicture');
var user = firebase.auth().currentUser;
image.getDownloadURL().then((url) => {
user.updateProfile({
photoURL: url
}).then(() =>{
console.log("updete succefully");
updeteUser();
}).catch(error =>{
console.log("error!!",error);
});
});
};
export const updeteUser=()=>{
const dispatch=useDispatch();
var user = firebase.auth().currentUser;
dispatch(actions.updateUser(user));
}
How can I avoid this?
This is the hook you are using:
const dispatch=useDispatch();
You can only use hooks inside a React functional component. Right now you are trying to use this hook in a normal javascript function.