How to export function and import react hooks - reactjs

I know and know how to do it but it causes problems for me
I just want to import the functions {OnSubmitLog_In and username} and maybe more how to listing it right is not going to make it a problem
2 js files
the first is imports like this
import * as Login from './log_in';
import { OnSubmitLog_In, username } from './log_in';
In the second file
async function OnSubmitLog_In(e) {
e.preventDefault();
var data = { username, password }
await axios.post("http://localhost:4000/users/signin", data, {
}).then((response) => {
if (localStorage.getItem('token', response.data.accessToken)) {
alert('user alredy in')
} else {
alert('hellow ' + data.username)
localStorage.setItem('token', response.data.accessToken)
console.log('response data', response.data)
console.log('response config', response.config.data)
}
}, (error) => {
console.log('error', error)
if (405) {
alert('user not found')
} else if (500) {
alert('user not found try again')
}
});
}
export default Log_In;
this is the error
./src/NAVBAR/nav.js
Attempted import error: 'OnSubmitLog_In' is not exported from './log_in'.

You are exporting as default, you should import like this,
import OnSubmitLog_In from './log_in'; //Not sure about username
Update
To import everything from a single file as,
import * as Login from './log_in'
You need to export everything as named export from log_in file.
For example, this is my log_in file,
import React from 'react'
export const MyComponent = () => {
return <div>Component 1</div>
}
export const MyComponent2 = () => {
return <div>Component 2</div>
}
Now you can use those components in parent component like,
<Login.MyComponent />
<Login.MyComponent2 />
Demo

You should export you functions in an object to import them the way you do.
Like this:
async function OnSubmitLog_In(e) {
e.preventDefault();
var data = { username, password }
await axios.post("http://localhost:4000/users/signin", data, {
}).then((response) => {
if (localStorage.getItem('token', response.data.accessToken)) {
alert('user alredy in')
} else {
alert('hellow ' + data.username)
localStorage.setItem('token', response.data.accessToken)
console.log('response data', response.data)
console.log('response config', response.config.data)
}
}, (error) => {
console.log('error', error)
if (405) {
alert('user not found')
} else if (500) {
alert('user not found try again')
}
});
}
export {
OnSubmitLog_In
};

You have to import code as below.
import OnSubmitLog_In, { username } from './log_in';
Here you are exporting as default. If you remove default then you have to write code as below.
import { OnSubmitLog_In, username } from './log_in';

Related

how to pass token in headers in below reactjs codesandbox link

https://codesandbox.io/s/login-authentication-usecontext-66t9t?file=/src/index.js
Here how we can pass token in headers for any other pages in codesandbox link. In my code i have action file like this. im getting my response in localstorage.how can i pass my accesstoken here as headers in this page.
import axios from 'axios';
export const upiAction = {
upi,
};
function upi(user) {
return (dispatch) => {
var data = {
upiId: user.upiId,
accountNumber: user.accountNumber,
};
axios
.post('http://localhost:9091/upiidcreation', data
)
.then((res) => {
console.log("res", (res));
const { data } = res;
alert(JSON.stringify(data.responseDesc));
// window.location.pathname = "./homes";
if (data.responseCode === "00") {
window.location.pathname = "./home"
}
})
.catch(err => {
dispatch(setUserUpiError(err, true));
alert("Please Check With details");
});
};
}
export function setUserUpi(showError) {
return {
type: 'SET_UPI_SUCCESS',
showError: showError,
};
}
export function setUserUpiError(error, showError) {
return {
type: 'SET_UPI_ERROR',
error: error,
showError: showError,
};
}

how to pass login token in headers in other pages in react redux

Here i have my upi action folder ,here how can i add my jwt token from login page api to this page. what is the procedure for displaying token genereated from login page to be used in other pages in react.
import axios from 'axios';
export const upiAction = {
upi,
};
function upi(user) {
return (dispatch) => {
var data = {
upiId: user.upiId,
accountNumber: user.accountNumber,
};
axios
.post('http://localhost:9091/upiidcreation', data)
.then((res) => {
console.log("res", (res));
alert(JSON.stringify(res.data.responseDesc));
// window.location.pathname = "./homes";
})
.catch(err => {
dispatch(setUserUpiError(err, true));
alert("Please Check With details");
});
};
}
export function setUserUpi(showError) {
return {
type: 'SET_UPI_SUCCESS',
showError: showError,
};
}
export function setUserUpiError(error, showError) {
return {
type: 'SET_UPI_ERROR',
error: error,
showError: showError,
};
}
You can import your redux store in any file and then use the getState() function to get the current redux state.
Example:
import store from './store'
console.log('Current state: ', store.getState())
// {tokens: [...], otherState: {...}}
https://redux.js.org/tutorials/fundamentals/part-4-store#redux-store

Next.js - React Custom Hook throws Invalid hook call

Hi I am quite new to react and this is for a learning project.
In react under next.js want to check for the existence of a certain folder on the server. To achieve that I implemented an api twigExists.js in pages/api and a custom hook twigExistsRequest.js in the library folder:
import {useEffect, useRef} from "react";
import {webApiUrl} from "#/library/webHelpers";
export function useTwigExistsRequest({
parentDirSegment,
name,
action,
treeStateDispatch
}) {
const nameExists = useRef('not');
useEffect(() => {
if ('' !== name) {
async function fetchNameValidation() {
try {
const response = await fetch(
webApiUrl() + '/branchName',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({parentDirSegment, name})
}
);
const answer = await response.json();
if (undefined !== answer['exists']) {
nameExists.current = answer['exists'];
}
else if (undefined !== answer['err']) {
console.log(answer['err']);
}
} catch (err) {
console.log(err);
}
}
fetchNameValidation().then(() => {
nameExists.current === 'exists'
&& treeStateDispatch({
action,
name,
dirSegment: parentDirSegment
});
})
}
});
}
The following error is thrown at the useRef line, line 10:
Error: Invalid hook call. Hooks can only be called inside of the body
of a function component.
I am using an almost identical approach to get the structure of a special folder with its subfolders and it is working fine. Working example:
import {useEffect, useRef} from "react";
import {webApiUrl} from "#/library/webHelpers";
export default function useChangeBranchRequest({
data,
setData
}) {
let postData;
const storeEffect = useRef(0);
if ('skip' !== data) {
storeEffect.current += 1;
postData = JSON.stringify(data);
}
useEffect(() => {
if (0 !== storeEffect.current) {
async function fetchData() {
try {
const response = await fetch(
webApiUrl() + '/changeBranch',
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: postData
});
const json = await response.json();
setData(JSON.parse(json['tree']));
} catch (error) {
console.log(error);
}
}
fetchData()
.then(() => {
return (<></>);
});
}
}, [storeEffect.current]);
}
I can't see: What is wrong in the first example??
Edit due to question: useTwigExistsRequest is called from this file:
import {useTwigExistsRequest} from "#/library/twigExistsRequest";
export default function twigExistsHandler({
parentDirSegment,
name,
action,
treeStateDispatch
}) {
useTwigExistsRequest({
parentDirSegment,
action,
name,
treeStateDispatch
});
}
trying to avoid a direct call from:
import {ACTIONS} from "#/library/common";
import {useState} from "react";
import twigExistsHandler from "#/library/twigExistsHandler";
export default function PlgButton({dirSegment, action, text, treeStateDispatch}) {
const [info, SetInfo] = useState('');
const [parentDirSegment, SetParentDirSegment] = useState('');
// name validation, triggered by SetInfo. Returns strings 'false' or 'true':
// reset Button after execution
if (info) SetInfo('');
return (
<button
className="btn btn-secondary btn-sm new-plg-btn"
onClick={() => {
clickHandler(action);
}}
>
{text}
</button>
);
function clickHandler(action) {
let name;
switch (action) {
case ACTIONS.add:
name = window.prompt('New name:');
twigExistsHandler({
parentDirSegment: dirSegment,
name,
action,
treeStateDispatch
});
break;
case ACTIONS.dup:
name = window.prompt('Dup name:');
twigExistsHandler({
parentDirSegment: dirSegment.slice(0,dirSegment.lastIndexOf('/')),
name,
action,
treeStateDispatch
});
break;
case ACTIONS.del:
window.confirm('Irrevocably delete the whole playground?')
&& treeStateDispatch({
info: '',
dirSegment,
action
});
break;
}
}
}

React-Query how to get error message from onError callback?

I have small application where I am using React-Query, The problem is that when I try to activate onError callback, React Query first time checks onSuccess callback Even when the post request data is incorrect, and throws an error
TypeError: Cannot destructure property 'token' of 'data' as it is undefined.
at Object.onSuccess
But actual API response is {response: null, error: "Unauthorised"}
error: "Unauthorised"
response: null
My problem is that I can't access error response from onError callback, What am I doing wrong?
/**
* /* eslint-disable
*
* #format
*/
import { useMutation } from 'react-query';
import { useNavigate } from 'react-router-dom';
import AuthController from '../../../controller/auth';
import { useToasts } from 'react-toast-notifications';
const Login = () => {
return AuthController.Login('user4', 'wrongpass');
};
export default function useUserLogin(setCheckTokenStatus) {
const { addToast } = useToasts();
const navigate = useNavigate();
return useMutation(Login, {
onSuccess: (data) => {
console.log('succ');
let {
token,
tokenExpiresAt,
user: { firstname }
} = data;
setCheckTokenStatus(token);
localStorage.setItem('idToken', JSON.stringify(token));
localStorage.setItem('expires', JSON.stringify(tokenExpiresAt));
navigate('/dashboard', {
replace: true
});
addToast(`hello ${firstname}!`, { appearance: 'success', autoDismiss: true, autoDismissTimeout: 3000 });
},
onError: (error) => {
console.log(error);
addToast(`error: ${error}`, {
appearance: 'error',
autoDismiss: true,
autoDismissTimeout: 3000
});
}
});
}
/** #format */
//AuthController
import myAPI from '../../config/api/index';
export default class AuthController {
static async Login(mobile, password) {
let data = {
mobile,
password,
role: 1
};
try {
const response = await myAPI.post(`/login`, data);
return response.data;
} catch (err) {
console.log('error occured');
}
}
}

Axios result undefined inside render() method in React

I'm trying to do axios.get() request inside my react component:
I'm fetching this data from my mongo database and nodejs server is running on localhost:9000:
This is my code:
import React, { Component } from 'react'
import axios from 'axios';
export default class Home extends Component {
state = {
data : []
}
async componentDidMount() {
const {data} = await axios.get("http://localhost:9000/data")
this.setState({data});
console.log(this.state.data)
}
render(){
console.log(this.state.data);
return (
<div>
{this.state.data[0]['title']}
</div>
);
}
}
Problem is that {this.state.data[0]['title']} says
cannot read property 'title' of undefined
How can I correct this?
Thanks in advance
try it:
axios.get('http://localhost:9000/data')
.then(function (response) {
// handle success
this.setState({data:response.data});
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
and I think you must be used this like:
state = {
data : [{
_id:"",
what:"",
title:"",
__v:0
}]
}
{this.state.data[0].title}

Resources