I have a select on car name which displays the car colour. When I input a car in the car field and it exists in the car list, I display the colour in Maintain (this works)
If I change the colour on the currently selected car and save the change, I want the updated colour to appear in the input box of the principle child (Cars)
It works if I re-select the car, but I want it to update as soon as the save button is clicked.
How can I get the colour to update on save?
Here is the REPL
App.svelte
<script>
import Cars from './Cars.svelte'
import MaintainCar from './MaintainCar.svelte'
let cars = {'Audi': 'red', 'BMW':'blue', 'Hillman': 'green'}
function maintenance() {
console.log(cars)
}
</script>
<main>
<Cars cars={cars}/>
<MaintainCar cars={cars} on:message={maintenance} />
</main>
Cars.svelte
<script>
export let cars
export let selected_car = ''
let colour = ''
let car_list = getCars(cars)
$: colour = cars[selected_car]
function getCars(cars) {
let car_list = []
for (const [key, value] of Object.entries(cars)) {
car_list.push(key);
}
if (!selected_car) {
selected_car = car_list[0]
colour = cars[selected_car]
}
return car_list
}
function selectCar() {
colour = cars[selected_car]
}
</script>
<select bind:value={selected_car} on:click={selectCar}>
{#each car_list as car}
<option value={car}>
{car}
</option>
{/each}
</select>
<input type="text" bind:value={colour} placeholder="colour"/>
MaintainCar.svelte
<div>
<input type="text" bind:value={car} placeholder="car"/>
<input type="text" bind:value={colour} placeholder="colour"/>
<div>
<button class="select-button" on:click={saveData}>Save</button>
</div>
</div>
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
export let cars
let car = ''
$: colour = checkCar(car)
function checkCar(car) {
colour = '';
if (car && car in cars) {
colour = cars[car];
}
return colour
}
function saveData() {
cars[car] = colour;
car = ''
colour = ''
dispatch('message', {
text: 'colour'
});
}
</script>