S
SolidJS4mo ago
Mr Void

Reset signals when prop value changes

How can I reset the showFront state of Card when Card's props.data changes?
type CardProps = {
data: Card
}

const Card = (props: CardProps) => {
const [showFront, setShowFront] = createSignal<boolean>(true)
// ...
}
type CardProps = {
data: Card
}

const Card = (props: CardProps) => {
const [showFront, setShowFront] = createSignal<boolean>(true)
// ...
}
return (
<Container>
<Card data={currentCard()} />
<!-- buttons to navigate between cards -->
</Container>
)
return (
<Container>
<Card data={currentCard()} />
<!-- buttons to navigate between cards -->
</Container>
)
5 Replies
Mr Void
Mr VoidOP4mo ago
Currently resetting this way, is there a better way? :
const [currentCardId, setCurrentCardId] = createSignal<string | null>(null)

const Card = () => {
// ...
createEffect(() => {
if (currentCardId() === null) {
setCurrentCardId(props.data.id)
} else if(currentCardId() !== props.data.id) {
batch(() => {
setCurrentCardId(props.data.id)
setShowFront(true)
})
}
})

// ...
}
const [currentCardId, setCurrentCardId] = createSignal<string | null>(null)

const Card = () => {
// ...
createEffect(() => {
if (currentCardId() === null) {
setCurrentCardId(props.data.id)
} else if(currentCardId() !== props.data.id) {
batch(() => {
setCurrentCardId(props.data.id)
setShowFront(true)
})
}
})

// ...
}
foolswisdom
foolswisdom4mo ago
Generally speaking, what you're looking for is a writeableMemo. I believe #solid-primitives has an implementation you can use
Mr Void
Mr VoidOP4mo ago
I tried the following and doesn't cause re-rendering for all Card components, is this a decent solution or should I use createWritableMemo ?
const Card = (props) => {
let prevId = props.data.id;

createEffect(() => {
if (prevId !== props.data.id) {
prevId = props.data.id
setShowFront(true)
}
}
}
const Card = (props) => {
let prevId = props.data.id;

createEffect(() => {
if (prevId !== props.data.id) {
prevId = props.data.id
setShowFront(true)
}
}
}
foolswisdom
foolswisdom4mo ago
Nah, I didn't quite realize your use case Not quite a fit Anyway, if it works it works
NitonFx
NitonFx4mo ago
i mean one should not read a prop in the main body of the component afaik wouldn't this be cleaner
const Card = (props) => {
createEffect(on(props.data, (_) => {
setShowFront(true)
}))
}
const Card = (props) => {
createEffect(on(props.data, (_) => {
setShowFront(true)
}))
}
Want results from more Discord servers?
Add your server