I am trying to use state variable from a client component which accepts certain form values from the user in component A and then I need to use those values in component B which is a server component and is mainly responsible for querying a .XML file with the form values.
However, let's say if I have two files in the app directory called A.tsx and B.tsx. How do I access the 'aValues' in B.tsx?
A.tsx:
'use client'
import { useState } from "react"
const A = () => {
const [aValues, setAValues] = useState({
name: '',
phone: ''
});
return (
<div>A is a Client component</div>
)
}
export default A
B.tsx:
const B = () => {
return (
<div>B is a Server component and wants to display the aValues</div>
)
}
export default B
- I tried adding a Link tag and importing it in the b using useSearchParams but then I need to change component B to client as well.
A.tsx:
<Link href={{ pathname: 'b', query: {aValues: JSON.stringify(aValues)}}}> B </Link>
B.tsx:
'use client'
import {useSearchParams} from 'next/navigation'
const B = () => {
const searchParams = useSearchParams()
const aValues = searchParams.get('aValues')
const result = JSON.parse(aValues)
<div>{result.name}</div>
}
export default B
I also tried creating a global state with Redux and use it but felt it to be rather too complicated and a bit of an overkill for the task.
Additionally, I also tried creating a new C.tsx and importing <A/> and <B/> just to pass the aValues as children in B but still couldn't do it.
C.tsx
import A from 'A'
import B from 'B'
const C = () => {
return (
<div>
<A>
<B name={aValues.name} phone={aValues.phone}/>
</A>
</div>
)
}
export default C