Home > Software engineering >  Page redirect after user authenticate in React
Page redirect after user authenticate in React

Time:01-21

how can i redirect a user to a page he was previously in(let's say a detail page) or a page he's trying to access after successfully authenticating in react just like the request.GET.next in django with regular templates, i am using formik and django knox authentication for my server side. i know of the useLocation() hook, if so how can i store the previous or next url path in the uselocation state dynamically.

AUTH.JS

const {setIsLoggedIn,setUserData,isloggedIn,}=useContext(AuthContext)



const location=useLocation()

// console.log(location.state.from)
const loginformik=useFormik({
    initialValues:{
        // firstName:"",
        // lastName:"",
        email:"",
        password:"",   
    },
    validationSchema:Yup.object({
        email:Yup.string().email('invalid email address').required(),
        password:Yup.string().min(6,'password must be more than characters').required(),
    }),
    onSubmit:(values=>{
        fetch('http://127.0.0.1:8000/auth/login',{
            method:'POST',
            headers: {
                'Content-Type': 'application/json'
                // 'Content-Type': 'application/form-data',
              },
              body: JSON.stringify(values)

        }).then(res=>res.json()).then(data=>{
            
            console.log(data)
            localStorage.setItem('token',data.token)
            setUserData(data.user)
            setIsLoggedIn(true)
            if (data.status=== 202){
                setIsLoggedIn(true)
            }
        })
        
    })
})

DETAIL.js

const getPosts=async ()=> {
    const token=localStorage.getItem('token')
    console.log(token)
    const response= await fetch(`http://127.0.0.1:8000/${id}/`,{
        method:'GET',
        headers:{
            'Accept': 'application/json',
            'Authorization':`Token ${token}`,
            'Content-Type': 'application/json'
        }
    })
    console.log(response.url)
    if (response.status===401){
        navigate(`/auth?login`)
        localStorage.setItem('next_url',response.url)
    }
    const data=await response.json()

    setPost(data.music)

}

CodePudding user response:

Use react router Dom 6. It has useNavigation hook which works well. And u can do navigation programmatically.

CodePudding user response:

In the Detail component use the useLocation hook to pass along the current location so that the Auth component knows where it can redirect back to.

Detail

import { ..., useLocation, useNavigate } from 'react-router';

...

const navigate = useNavigate();
const location = useLocation();

...


const getPosts = async () => {
  const token = localStorage.getItem('token');
  console.log(token);
  const response = await fetch(`http://127.0.0.1:8000/${id}/`, {
    method:'GET',
    headers:{
      'Accept': 'application/json',
      'Authorization':`Token ${token}`,
      'Content-Type': 'application/json'
    }
  });
  console.log(response.url);
  if (response.status === 401) {
    navigate(
      "/auth?login",
      {
        state: { from: location }, // <-- pass current location
        replace: true
      }
    );
    localStorage.setItem('next_url',response.url);
  }
  const data = await response.json();

  setPost(data.music);
}

Auth

import { ..., useLocation, useNavigate } from 'react-router';

...

const { setIsLoggedIn, setUserData, isloggedIn } = useContext(AuthContext);

const navigate = useNavigate();
const location = useLocation();

const loginformik = useFormik({
  initialValues: {
    // firstName:"",
    // lastName:"",
    email:"",
    password:"",   
  },
  validationSchema: Yup.object({
    email: Yup.string()
      .email('invalid email address')
      .required(),
    password: Yup.string()
      .min(6,'password must be more than characters')
      .required(),
  }),
  onSubmit: values => {
    fetch('http://127.0.0.1:8000/auth/login', {
      method:'POST',
      headers: {
        'Content-Type': 'application/json'
        // 'Content-Type': 'application/form-data',
      },
      body: JSON.stringify(values)
    })
      .then(res => res.json())
      .then(data => {
        console.log(data);
        localStorage.setItem('token', data.token);
        setUserData(data.user);
        setIsLoggedIn(true);
        if (data.status === 202) {
          setIsLoggedIn(true);
        }

         // Redirect back to previous location, or home
        const { state } = location;
        const { from } = state || { from: { pathname: "/" } };
        navigate(from, { replace: true });
      });
  },
});
  • Related