fetching data from a component modified by another component in Svelte

In this particular component, I am capturing user input and storing it in variables. I would like this value to be automatically updated in another component when the submit button is clicked.

<script>
  import { onMount } from "svelte";
    let url=[];
onMount(() => {
  onClickGetNotes()
});
    async function onClickGetNotes() {
            console.log(url.url)
  }
  </script>

<form on:submit|preventDefault={onClickGetNotes}>
    <input label="url" bind:value={url.url} placeholder="enter id here"/>
    <button>Submit</button>
</form>

This second component is where I need the entered URL to be dynamically updated for an image overlay using Leaflet.

<script>
  import { onMount } from "svelte";
import L from "leaflet";

 var url
 var map
 var layerGroup
// code for map

onMount(() => {
   map = L.map('issmap', {
  .....
  crs: L.CRS.Simple
});
var w = 500,
    h = 500,
    url = 'https://pp.vk.me/c837734/v837734326/d436/zlt_Wifq2NU.jpg';
 ......
layerGroup = L.layerGroup().addTo(map);
});
  </script>

.....

The main goal is to retrieve the user's URL input and reflect it accurately on the Leaflet map.

Any suggestions on how to achieve this?

Answer №1

There are a couple of different approaches to accomplish this task.

If both elements belong to the same parent component, one option is to define the variable in the parent component and then pass it up to the form component using either the bind: syntax or by creating an event dispatcher to transfer the information back down to the other element.

Alternatively, you can create a writable store in a separate file, import it into both components, and any updates made to the store in one component will automatically reflect in all others.

A (not quite) third possibility involves the parent component declaring the store and passing it down to descendants using setContext. This allows all descendants—beyond just children—to access the store's data. The advantage here is that the shared data is contained within a specific section of your application, rather than being global.

Answer №2

To implement Context API and Writable Store, follow this example:

<script>
  import { onMount, setContext } from "svelte";
  import {writable} from 'svelte/store'

  let url= writable("");
  
  setContext("c", url)
  onMount(() => {
   onClickGetNotes()
  });
    async function onClickGetNotes() {
            console.log($url)
  }
  </script>

<form on:submit|preventDefault={onClickGetNotes}>
    <input label="url" bind:value={$url} placeholder="enter id here"/>
    <button>Submit</button>
</form>

...

<script>
      import { onMount, getContext } from "svelte";
      import L from "leaflet";

      // to access the value use $url
      let url = getContext("c")
    
    </script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Aligning SVG shapes within each other

I recently encountered a scenario where I needed to position SVG shapes in the center of each other with varying scales. For instance, placing a rectangle or triangle within the center of a circle. While I found some solutions that worked for shapes like ...

Modify the data displayed on the chart by choosing the desired year from the dropdown options

In my Angular app, I am showcasing a chart that visualizes data based on selected starting and ending years from dropdown menus. The X axis represents 18 cities, while the Y axis displays "IAP" values. To calculate the "IAP" values for each city within the ...

Guide on how to retrieve a value using image.onload on the client side

I have encountered an issue with exporting a png image from an svg element using Blob. The problem arises when clicking the anchor tag to export the image, as the content is not rendered due to the asynchronous method (image.onload()) being called after th ...

"415 (Unsupported Media Type) encountered when making a POST request in a REST API

I've encountered an issue with a React component where a checkbox triggers a POST request to a REST API with a single parameter. Despite setting a breakpoint in the WebAPI code, it's not being hit and I'm receiving a 415 Unsupported Media Ty ...

Is it achievable to selectively target a particular class without resorting to utilizing an ID within DOM manipulation?

Is there a way to apply a function to a specific class without requiring an id? For example, in CSS hover effects, where multiple elements share the same class but only the one being hovered over is affected. function toggleHeight(elementId, arrowId) { ...

Tips for expanding a fabric canvas to match the entire width of its parent division

specific scenario I have a cloth canvas placed inside a main section. How can I expand the canvas to cover the entire width and height of its container? Here is what my current code looks like: <div class="design_editor_div"> &l ...

The xslt code is failing to invoke the JavaScript function

I am currently utilizing xslt for the transformation of xml to html. Below is an example of an .xml file. <ImportOrganizationUtility-logging> <log-session module-name="ImportOrganizationUtility" end="17:54:06" start="17 ...

Is it possible to instantiate a Backbone view by referencing its string name that is stored within a JavaScript object?

I am currently working on a visual builder that utilizes different views for each component. Each view is defined as shown below: $(function() { var parallaxView = new Backbone.view.extend({ .... }); var parallaxView = new Backbone.view.e ...

Significant issue identified with ajax functionality, requiring immediate attention

After executing the code in the console, I expected to see the ajax object with a readyState of 0 (as I aborted the ajax call). However, Chrome is displaying the number 4 in the console instead of 0. This discrepancy is surprising. http://jsfiddle.net/8yC ...

How to use Javascript to toggle a popup containing an autoplaying Vimeo video

I am looking to create a pop-up window containing a Vimeo video inside. I have a div on my webpage with an id of "showVideo". When this div is clicked, I want to display a pop-up (new div with the id of "opened-video"). The "opened-video" div contains an i ...

Ionic - Error: SyntaxError: Unexpected token caught

I am currently utilizing Ionic Framework version 1.7.16 The error on Android is pinpointed to the following line of code var obj = {[$myid] : firebase.database.ServerValue.TIMESTAMP}; No error occurs when the line above is changed to the following var ...

Updating the list in React upon form submission without requiring a full page refresh

Currently, I have a list of data being displayed with a specific sort order in the textbox. Users are able to modify the order and upon clicking submit, the changes are saved in the database. The updated list will then be displayed in the new order upon pa ...

Node.js for Streaming Videos

I am currently working on streaming video using node.js and I recently came across this helpful article. The setup works perfectly when streaming from a local source, but now I need to stream the video from a web source. However, my specific requirement i ...

Exploring the Node Promise Chain: Utilizing Local Functions and Managing Multiple Value Passing in a Code Review

Upon reviewing the code provided, several questions have arisen: #1 I am curious about the best way to make the values returned by the bluebird.all functions accessible in subsequent functions. Is using the this-context a viable option without declaring t ...

Is there a way to detect when the mobile keyboard is open in a React application?

I am currently working with a Textfield that includes the Autofocus attribute. I am wondering if there is a method to detect when the keyboard opens in mobile view and then store this information in a boolean variable. https://i.stack.imgur.com/z0EtB.png ...

Substitute the symbol combination (][) with a comma within Node.js

Currently, I am utilizing Node JS along with the replace-in-file library for my project. Within a specific file named functions.js, I have implemented various functions. Furthermore, in another file named index.js, I have added code to call these functio ...

Tips for seamless integration of Crashlytics with your React Native application

As I work on developing my app with React Native, I am looking to capture crashes that occur on both the Objective-C and JavaScript aspects of the application. After following Crashlytics SDK's installation guide, I successfully implemented it into m ...

Occasionally, the Array.filter() method might strip away every element within the array

This situation is really frustrating me. The goal is to have the newArray return all elements except the one where the two ids match, as specified in the code. However, when I add objects to the array and then try to remove them one by one, the results are ...

I'm looking to learn how to efficiently write file chunks from a video upload in Node Js. How can I

My current project involves attempting to stream webcam or audio data to Node.js and save it on disk. The aim is to send the chunks of data to the server as soon as they are available. I have successfully captured the stream using getUserMedia, set up me ...

Picking specific <button> items

Presented here are a series of buttons to choose from: <button id="hdfs-test" type="button" class="btn btn-default btn-lg">HDFS</button> <button id="hive-test" type="button" class="btn btn-default btn-lg">HIVE</button> <button id ...