Как я могу импортировать этот компонент тостов в свою кнопку?

#javascript #reactjs #next.js

Вопрос:

Я новичок в Next.js и реагировать в целом. У меня есть кнопка, которая запускает внешний файл JavaScript ( query.js ), когда это будет сделано, я хочу показать тост, подтверждающий успех или неудачу. Я получил красивое всплывающее сообщение из этого репозитория, но я понятия не имею, как его интегрировать.

Вот мое index.js досье

 import {proses} from '../public/static/query.js'
import Notifications from './Notifications'
import useSWR from 'swr'

const fetcher = (...args) => fetch(...args).then(res => res.json())
function Profile() {
  const { data, error } = useSWR('a link here', fetcher)

  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>

  return data
}

export default function Home() {

  //fetching data
let data = Profile();
  return (
    //some code

        <button className={styles2.btnNormal} onClick={(e) => {
                                                                let result = proses(data)
                                                                if(result=="Copied to Clipboard!"){
                                                                  <Notifications /> 
                                                                  console.log("copied to clipboard!")
                                                                } else {
                                                                  console.log("not found")
                                                                }
                                                                }}>Process</button>
        
    
    //another code
  )
}
 

Вот Notifications.js .

 import React, { Component } from 'react';
import NotificationAlert from 'react-notification-alert';

var options = {};
options = {
    place: 'tc',
    message: (
        <div>
            Copied to Clipboard!
        </div>
    ),
    type: "success",
    icon: "now-ui-icons ui-1_bell-53",
    autoDismiss: 1.25
}

class Notifications extends Component {
    myFunc(){
        this.refs.notify.notificationAlert(options);
    }  
    render() {
        return (
            <div>
                <NotificationAlert ref="notify" zIndex={9999} onClick={() => {}} />
                <button onClick={() => this.myFunc()}>Hey</button>
            </div>
        );
    }
}

export default Notifications;
 

Вот мой внешний файл .js ( query.js ).

 export function proses(data) {
    //I named it data but it is actually closer to a database. I saved a list of items in google sheet. I want to lookup an item based on user input in the list and I want to do it fully on client side because it's extremely fast.
    //some client side data processing to lookup data
    //by the time this function executed the data should already fetched
    //the function will return a string "Copied to Clipboard!" if it found a match or "not found" if it doesn't
};
 

По сути, я не знаю, как изменить Notifications.js , чтобы вызывать только тост, а не пример кнопки внутри него.

Комментарии:

1. Как вы узнаете, когда ваш внешний скрипт будет выполнен, proses возвращает ли функция что-нибудь?

2. @juliomalves возвращает строку

Ответ №1:

Выполнение действия как/в результате асинхронной функции (все запросы api и запросы к базе данных) будет выполняться с помощью обратных вызовов, обещаний или async await . Не видя, как вы «просматриваете» данные, трудно сказать, какие из них вы будете использовать, но вот пример для обратных вызовов.

обратный звонок

 function process(data, callback) {
// Format data into a useable query string
  callbackStyleQuery(queryString, (err, result) => {
    If (err) {
      callback(err);
    } else {
       callback(null, result)
    }
})};
 

Затем внутри вашего обработчика щелчков вы бы поместили

 (e)=>{process(data, (err, result) => {
  If (err) {
    // handle appropriately
  } else {
    // do whatever you want with the result.   
  }
})
 

Простите все странности в компоновке. Я напечатал это на своем телефоне.

Комментарии:

1. спасибо за указатель! Я добавил код, в котором я получаю данные, к тому времени query.js выполняется, это не совсем асинхронно. вы не могли бы взглянуть? Я все еще не знаю, как изменить компонент тостов. Я даже не знаю, с чего начать.