Redirect to URL from collection

Hi, I have a collection called renderIds that has some URLs in a field called title . What I want to do is: when a user clicks on button1 , redirect that user to the first URL in the collection renderIds . However, when I click on button1 in the live website, nothing happens. If I log url, it correctly logs the URL of the first item. I think there is something wrong with the wixLocation call, but I cannot figure out what :confused:

Here is my code:

import wixLocation from 'wix-location';
import wixData from 'wix-data';

$w.onReady(function () {});
export function button1_click(event) {
    wixData.query('renderIds')
        .find()
        .then(results => {
            console.log(results);
            let resultCount = results.totalCount;
            if (resultCount !== 0) {
                let firstItem = results.items[0];
                let url = firstItem.title;
                wixLocation.to(url);
            }
        });
}

And here is the collection:

Can you please post one of these URLs here (not a screenshot)?.

Sure, here it is: https://cdn.shotstack. io/au/stage/ztk4cjthu7/7ff195fc-26b4-4dbe-9a59-a6a472b093ce.mp4
(I had to insert a space before " .io " as I am apparently not allowed to post links, so please remove the space when you paste it).
The URLs in the collection are all the same, as I am just testing that the redirect works for now. You should be seeing a video if you visit that URL.

The query result doesn’t have a totalCount property. You want to use results.length or results.items.length to see if the query returned any results. See the WixDataQueryResult API for more information.

Unfortunately that doesn’t seem to be the problem. I put a console.log inside the if statement too and it does get executed, it actually prints the correct url (which means the query returns the correct item).

How about hard coding one of the URLs into the wixLocation.to() function and seeing if that works. There might be a problem with setting the url variable since the Title field in the collection is a text field - and not url . Maybe try using a url field in the collection.

The only thing I can think of is that perhaps the url has to be displayed in an iFrame or some other HTML oddness. You might try the Link Button example and see if the Custom Element code redirects OK.

I actually did try Google’s url in wixLocation.to( ) function: the oddest thing is that if I put the wixLocation.to() before the wixData.query(), then the redirect to Google or any link works. However, if I put the wixLocation.to() function at any point after the query function, the redirect does not work anymore, not even to a hardcoded url like Google.
I also tried with both text or url in the collection and it makes no difference.
At this point, I am thinking this might be a problem of timing between the query and the wixLocation functions? I really don’t know what to try anymore :smiling_face_with_tear:

Ok, so after many tries, I figured that there was a timing problem, so I now rewrote the code with async/await (see below code snippets). The wixLocation.to() function now works if I hardcode one of my URLs (or any URL) in it, but does not work if I pass the url directly from the collection. In this case I get this error:

UnsupportedLinkTypeError: Unsupported link type
    at Object.getLinkProps (linkUtils.ts:326:10)
    at Object.p (locationSdkFactory.ts:19:31)
    at Object.eval [as to] (active$wBiEvent.js:57:19)
    at c1dmp.js:10:9
    at u (runtime.js:63:40)
    at Generator.eval [as _invoke] (runtime.js:294:22)
    at Generator.eval [as next] (runtime.js:119:21)
    at u (c1dmp.js?wix-data-as-namespace=true&replace-console=false&dependencies-token=3938:1:1263)
    at c (c1dmp.js?wix-data-as-namespace=true&replace-console=false&dependencies-token=3938:1:1466)  

Frontend code:

import wixLocation from 'wix-location';
import { findUrl } from 'backend/serviceModule.jsw';

$w.onReady(function () {});

export async function button1_click(event) {
    let url = await findUrl();
    console.log(url);
    try {
        wixLocation.to(url);
    } catch (error) { console.log(error); }

}

Backend code:

import wixData from 'wix-data';

export async function findUrl() {
    try {
        const results = await wixData.query('renderIds').find();
        return results.items[0].videoUrl;
    }
    catch(error) {
        console.log(error);
    }
}

Any ideas? I feel like I am so close but still so far from a solution :grinning:

I have no idea.

The only thing I can think of, that you have some unusual browser security settings or browser extension/plugins that prevent navigating without a direct manual event (such as click without waiting for promise fulfillment).

OK - this has been bugging me, so even though it took away from my beer time, I decided to try it out for myself. I cobbled together an Interesting Sites example that lets the visitor choose a site from a dropdown and then click a button to redirect to that site. I tried to conform as closely as possible to the way that you are doing this.

It works just fine. I even tried a little experiment and used your URLs and they also worked. I really have no clue why this isn’t working for you. Perhaps the answer is beer.

Thank you! I guess this must be it, I really cannot think of anything else that could be going wrong :frowning:

haha best answer ever :grinning: well first of all thank you for sacrificing your beer to try this out, I appreciate that. I guess I will just try redirecting while drinking beer, maybe it works :sweat_smile:

Looking at your collection, I changed mine’s permission to “Site Content” (I had it set on “Form Submission” because I populate it from an external API). Now it works, it redirects correctly! However, I really need the permission to be “Form Submission”, otherwise the external API won’t be able to populate my collection :smiling_face_with_tear: Please tell me you understand what’s going on…

Unbelievable. I at first thought it was permissions, but you said you got valid results so I figured your permissions were OK. In any case…

Set the permission to Form Submission. Then in the backend code (the query), use the suppressAuth option in the find(), like this:

Set the options:

let options = {
 "suppressAuth": true
};

And then use the options in the find() function:

find(options)

I should have done something like this in my example in order to illustrate “best practices”. I’ll change it when I get a chance.

Just changed the example in order to demonstrate proper security/privacy practices.

Probably not needed for something like this, as the collection contents aren’t exactly top secret. But worth showing how it’s done.

Perfect! Thank you so much, I will change that in my code :slight_smile: I now have another question, here goes a new post…stay tuned :grinning: