I'm using Nuxt on a project that has a search input in the header.
I Implemented it using Mabpox Geocoder and it works fine but on first page load the search input appears like this

When the mounted hook gets executed and the plugin loads the geocoder it looks fine

I wanted to use the <client-only> tag to put a placeholder until the real search is fetched
But I get this error:
500 can't access property "querySelector", geocoderContainer is null
Search.vue:
<template>
<div>
<client-only>
<div :id="geocoderID" @resultFound="resultFound"></div>
</client-only>
</div>
</template>
<script>
export default {
computed: {
geocoderID() {
return `mapbox-geocoder-${this.containerID}`;
},
},
mounted() {
this.$mapboxMaps.createGeocoder(this.geocoderID);
},
}
</script>
My Mapbox.client.js plugin:
import "mapbox-gl/dist/mapbox-gl.css";
const mapboxgl = require("mapbox-gl");
import MapboxGeocoder from "@mapbox/mapbox-gl-geocoder";
import "@mapbox/mapbox-gl-geocoder/dist/mapbox-gl-geocoder.css";
export default function (context, inject) {
inject("mapboxMaps", { createGeocoder });
mapboxgl.accessToken = <my-access-token>
function createGeocoder(containerID) {
// Only add the search box if there's none (avoid duplications of boxes)
const geocoderContainer = document.getElementById(containerID);
if (geocoderContainer.querySelector(".mapboxgl-ctrl-geocoder")) return;
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
enableEventLogging: false,
mapboxgl: mapboxgl,
});
geocoder.addTo(geocoderContainer);
}
When I try to log the div to which i want to attach the search using the following
mounted() {
console.log(this.geocoderID);
console.log(document.getElementById(this.geocoderID))
this.$mapboxMaps.createGeocoder(this.geocoderID);
},
It logs this
mapbox-geocoder-nav-search
undefined
I found the answer in the docs

This is what I did
methods: {
renderSearch(count = 10) {
this.$nextTick(() => {
if (document.getElementById(this.geocoderID)) {
this.$mapboxMaps.createGeocoder(this.geocoderID);
} else if (count > 0) {
this.initClientOnlyComp(count - 1);
}
});
},
},
mounted() {
this.renderSearch();
},
It worked fine, I logged the count just for curiousity and the element was rendered at count = 9.