history.push에 data담아 보내기

OwlSuri·2022년 9월 21일
0

history.push는 주로 라우팅할때만 사용했었는데,
props로 내려주는 것 말고 이동한 url로 데이터를 날려주는 것이 필요했다.

찾아보니 history.push에 데이터를 담을 수 있었다...!

history.push로 데이터 날리기

  1. 데이터 보내는 곳
import { useHistory } from "react-router";
import { useState } from "react"
...

const history = useHistory();
const [data, setData] = useState({})

...

history.push({
	pathname: '경로',
    state: data    
    })
    
  1. 받는곳
import { useLocation } from "react-router";
...
const location = useLocation()
...

const currentData = location.state

그래서 바로 해보았는데....
하얀화면만 뜨고, 콘솔에 에러 메시지도 뜨지 않았다.

에러의 원인

url에 쿼리스트링이 들어있었다...
pathname에는 쿼리스트링이 포함되지 않는데...

해결

search에 쿼리스트링 부분을 넣어주었다(아래 코드)

import { useHistory } from "react-router";
import { useState } from "react"
...

const history = useHistory();
const [data, setData] = useState({})

...

history.push({
	pathname: '경로',
    search: '쿼리스트링'
    state: data    
    })

데이터도 잘 넘어오고, 라우팅도 잘된다...!!!

profile
기억이 안되면, 기록을 -

0개의 댓글